選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

64 行
2.2KB

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