You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

google_voice.py 1.5KB

1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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() + 'reply-' + 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