您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

47 行
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(
  21. '[Google] voiceToText text={} voice file name={}'.format(text, voice_file))
  22. reply = Reply(ReplyType.TEXT, text)
  23. except speech_recognition.UnknownValueError:
  24. reply = Reply(ReplyType.ERROR, "抱歉,我听不懂")
  25. except speech_recognition.RequestError as e:
  26. reply = Reply(ReplyType.ERROR, "抱歉,无法连接到 Google 语音识别服务;{0}".format(e))
  27. finally:
  28. return reply
  29. def textToVoice(self, text):
  30. try:
  31. mp3File = TmpDir().path() + '语音回复_' + str(int(time.time())) + '.mp3'
  32. tts = gTTS(text=text, lang='zh')
  33. tts.save(mp3File)
  34. logger.info(
  35. '[Google] textToVoice text={} voice file name={}'.format(text, mp3File))
  36. reply = Reply(ReplyType.VOICE, mp3File)
  37. except Exception as e:
  38. reply = Reply(ReplyType.ERROR, str(e))
  39. finally:
  40. return reply