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.

47 line
1.5KB

  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. mp3File = TmpDir().path() + "reply-" + str(int(time.time())) + ".mp3"
  31. tts = gTTS(text=text, lang="zh")
  32. tts.save(mp3File)
  33. logger.info("[Google] textToVoice text={} voice file name={}".format(text, mp3File))
  34. reply = Reply(ReplyType.VOICE, mp3File)
  35. except Exception as e:
  36. reply = Reply(ReplyType.ERROR, str(e))
  37. finally:
  38. return reply