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.

59 line
2.1KB

  1. """
  2. google voice service
  3. """
  4. import pathlib
  5. import subprocess
  6. import time
  7. import speech_recognition
  8. import pyttsx3
  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(new_file) as source:
  28. audio = self.recognizer.record(source)
  29. reply = {}
  30. try:
  31. text = self.recognizer.recognize_google(audio, language='zh-CN')
  32. logger.info(
  33. '[Google] voiceToText text={} voice file name={}'.format(text, voice_file))
  34. reply = {"type": "TEXT", "content": text}
  35. except speech_recognition.UnknownValueError:
  36. reply = {"type": "ERROR", "content": "抱歉,我听不懂"}
  37. except speech_recognition.RequestError as e:
  38. reply = {"type": "ERROR", "content": "抱歉,无法连接到 Google 语音识别服务;{0}".format(e)}
  39. finally:
  40. return reply
  41. def textToVoice(self, text):
  42. try:
  43. textFile = TmpDir().path() + '语音回复_' + str(int(time.time())) + '.mp3'
  44. self.engine.save_to_file(text, textFile)
  45. self.engine.runAndWait()
  46. logger.info(
  47. '[Google] textToVoice text={} voice file name={}'.format(text, textFile))
  48. reply = {"type": "VOICE", "content": textFile}
  49. except Exception as e:
  50. reply = {"type": "ERROR", "content": str(e)}
  51. finally:
  52. return reply