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

48 行
1.6KB

  1. """
  2. google voice service
  3. """
  4. import time
  5. import speech_recognition
  6. from gtts import gTTS
  7. from bridge.reply import Reply, ReplyType
  8. from common.log import logger
  9. from common.tmp_dir import TmpDir
  10. from voice.voice import Voice
  11. class GoogleVoice(Voice):
  12. recognizer = speech_recognition.Recognizer()
  13. def __init__(self):
  14. pass
  15. def voiceToText(self, voice_file):
  16. with speech_recognition.AudioFile(voice_file) as source:
  17. audio = self.recognizer.record(source)
  18. try:
  19. text = self.recognizer.recognize_google(audio, language="zh-CN")
  20. logger.info("[Google] voiceToText text={} voice file name={}".format(text, voice_file))
  21. reply = Reply(ReplyType.TEXT, text)
  22. except speech_recognition.UnknownValueError:
  23. reply = Reply(ReplyType.ERROR, "抱歉,我听不懂")
  24. except speech_recognition.RequestError as e:
  25. reply = Reply(ReplyType.ERROR, "抱歉,无法连接到 Google 语音识别服务;{0}".format(e))
  26. finally:
  27. return reply
  28. def textToVoice(self, text):
  29. try:
  30. # Avoid the same filename under multithreading
  31. mp3File = TmpDir().path() + "reply-" + str(int(time.time())) + "-" + str(hash(text) & 0x7FFFFFFF) + ".mp3"
  32. tts = gTTS(text=text, lang="zh")
  33. tts.save(mp3File)
  34. logger.info("[Google] textToVoice text={} voice file name={}".format(text, mp3File))
  35. reply = Reply(ReplyType.VOICE, mp3File)
  36. except Exception as e:
  37. reply = Reply(ReplyType.ERROR, str(e))
  38. finally:
  39. return reply