Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

52 Zeilen
1.7KB

  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. 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. return text
  34. except speech_recognition.UnknownValueError:
  35. return "抱歉,我听不懂。"
  36. except speech_recognition.RequestError as e:
  37. return "抱歉,无法连接到 Google 语音识别服务;{0}".format(e)
  38. def textToVoice(self, text):
  39. textFile = TmpDir().path() + '语音回复_' + str(int(time.time())) + '.mp3'
  40. self.engine.save_to_file(text, textFile)
  41. self.engine.runAndWait()
  42. logger.info(
  43. '[Google] textToVoice text={} voice file name={}'.format(text, textFile))
  44. return textFile