Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

51 lines
1.7KB

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