選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

pytts_voice.py 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. pytts voice service (offline)
  3. """
  4. import time
  5. import pyttsx3
  6. from bridge.reply import Reply, ReplyType
  7. from common.log import logger
  8. from common.tmp_dir import TmpDir
  9. from voice.voice import Voice
  10. import os
  11. class PyttsVoice(Voice):
  12. engine = pyttsx3.init()
  13. def __init__(self):
  14. # 语速
  15. self.engine.setProperty("rate", 125)
  16. # 音量
  17. self.engine.setProperty("volume", 1.0)
  18. for voice in self.engine.getProperty("voices"):
  19. if "Chinese" in voice.name:
  20. self.engine.setProperty("voice", voice.id)
  21. self.engine.setProperty("voice", "zh")
  22. def textToVoice(self, text):
  23. try:
  24. mp3FileName = "reply-" + str(int(time.time())) + ".mp3"
  25. mp3File = TmpDir().path() + mp3FileName
  26. self.engine.save_to_file(text, mp3File)
  27. self.engine.runAndWait()
  28. # engine.runAndWait() will return before the file created
  29. while mp3FileName not in os.listdir(TmpDir().path()):
  30. time.sleep(0.1)
  31. logger.info(
  32. "[Pytts] textToVoice text={} voice file name={}".format(text, mp3File)
  33. )
  34. reply = Reply(ReplyType.VOICE, mp3File)
  35. except Exception as e:
  36. reply = Reply(ReplyType.ERROR, str(e))
  37. finally:
  38. return reply