voicerss.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import requests
  2. from core import FileManager
  3. from core.TTS.TTSModule import TTSModule, FailToLoadSoundFile
  4. import logging
  5. logging.basicConfig()
  6. logger = logging.getLogger("kalliope")
  7. TTS_URL = "http://www.voicerss.org/controls/speech.ashx"
  8. TTS_CONTENT_TYPE = "audio/mpeg"
  9. TTS_TIMEOUT_SEC = 30
  10. class Voicerss(TTSModule):
  11. def __init__(self, **kwargs):
  12. super(Voicerss, self).__init__(**kwargs)
  13. def say(self, words):
  14. self.generate_and_play(words, self._generate_audio_file)
  15. def _generate_audio_file(self):
  16. # Prepare payload
  17. payload = self.get_payload()
  18. # getting the audio
  19. r = requests.get(TTS_URL, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  20. content_type = r.headers['Content-Type']
  21. logger.debug("Voicerss : Trying to get url: %s response code: %s and content-type: %s",
  22. r.url,
  23. r.status_code,
  24. content_type)
  25. # Verify the response status code and the response content type
  26. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  27. raise FailToLoadSoundFile("Voicerss : Fail while trying to remotely access the audio file")
  28. # OK we get the audio we can write the sound file
  29. FileManager.write_in_file(self.file_path, r.content)
  30. def get_payload(self):
  31. return {
  32. "src": self.words,
  33. "hl": self.language,
  34. "c": "mp3"
  35. }