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.

60 lines
2.1KB

  1. """
  2. google voice service
  3. """
  4. import time
  5. import speech_recognition
  6. import pyttsx3
  7. from gtts import gTTS
  8. from bridge.reply import Reply, ReplyType
  9. from common.log import logger
  10. from common.tmp_dir import TmpDir
  11. from voice.voice import Voice
  12. class GoogleVoice(Voice):
  13. recognizer = speech_recognition.Recognizer()
  14. engine = pyttsx3.init()
  15. def __init__(self):
  16. # 语速
  17. self.engine.setProperty('rate', 125)
  18. # 音量
  19. self.engine.setProperty('volume', 1.0)
  20. # 0为男声,1为女声
  21. voices = self.engine.getProperty('voices')
  22. self.engine.setProperty('voice', voices[1].id)
  23. def voiceToText(self, voice_file):
  24. # new_file = voice_file.replace('.mp3', '.wav')
  25. # subprocess.call('ffmpeg -i ' + voice_file +
  26. # ' -acodec pcm_s16le -ac 1 -ar 16000 ' + new_file, shell=True)
  27. with speech_recognition.AudioFile(voice_file) as source:
  28. audio = self.recognizer.record(source)
  29. try:
  30. text = self.recognizer.recognize_google(audio, language='zh-CN')
  31. logger.info(
  32. '[Google] voiceToText text={} voice file name={}'.format(text, voice_file))
  33. reply = Reply(ReplyType.TEXT, text)
  34. except speech_recognition.UnknownValueError:
  35. reply = Reply(ReplyType.ERROR, "抱歉,我听不懂")
  36. except speech_recognition.RequestError as e:
  37. reply = Reply(ReplyType.ERROR, "抱歉,无法连接到 Google 语音识别服务;{0}".format(e))
  38. finally:
  39. return reply
  40. def textToVoice(self, text):
  41. try:
  42. mp3File = TmpDir().path() + '语音回复_' + str(int(time.time())) + '.mp3'
  43. # self.engine.save_to_file(text, textFile)
  44. # self.engine.runAndWait()
  45. tts = gTTS(text=text, lang='zh')
  46. tts.save(mp3File)
  47. logger.info(
  48. '[Google] textToVoice text={} voice file name={}'.format(text, mp3File))
  49. reply = Reply(ReplyType.VOICE, mp3File)
  50. except Exception as e:
  51. reply = Reply(ReplyType.ERROR, str(e))
  52. finally:
  53. return reply