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.

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