问题描述
我正在尝试使用语音转文字来接受命令,并使用文字转语音来输出结果。
我有一个运行中的Python程序,可以使用gTTS将文本转换为语音。我有一个使用SpeechRecognition的有效python程序,可以收听我的麦克风并输出文本。两者结合会产生问题。如果在设置麦克风之前调用了文本转语音功能:
tts(“棕狐”)
microphone = sr.Microphone()
我得到音频。
如果我拨回电话,音频将永远不会播放。
以任何一种方式进行文字语音交流。我正在使用Logitech USB耳机。
import speech_recognition as sr
from gtts import gTTS
import pygame
import time,sys
from pygame import mixer
from io import BytesIO
def tts(text):
# initialize tts,create mp3 and play
tts = gTTS(text,lang='en')
fp = BytesIO()
tts.write_to_fp(fp)
fp.seek(0)
pygame.mixer.init()
pygame.mixer.music.load(fp)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
def recognize_speech_from_mic(recognizer,microphone):
"""Transcribe speech from recorded from `microphone`.
Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
"error": `None` if no error occured,otherwise a string containing
an error message if the API Could not be reached or
speech was unrecognizable
"transcription": `None` if speech Could not be transcribed,otherwise a string containing the transcribed text
"""
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer,sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone,sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# adjust the recognizer sensitivity to ambient noise and record audio
# from the microphone
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# set up the response object
response = {
"success": True,"error": None,"transcription": None
}
# try recognizing the speech in the recording
# if a RequestError or UnkNownValueError exception is caught,# update the response object accordingly
try:
response["transcription"] = recognizer.recognize_google(audio)
except sr.RequestError:
# API was unreachable or unresponsive
response["success"] = False
response["error"] = "API unavailable"
except sr.UnkNownValueError:
# speech was unintelligible
response["error"] = "Unable to recognize speech"
return response
if __name__ == "__main__":
# create recognizer and mic instances
recognizer = sr.Recognizer()
tts('brown fox')
microphone = sr.Microphone()
guess = recognize_speech_from_mic(recognizer,microphone)
#print("You said: {}".format(guess["transcription"]))
text = ("{}".format(guess["transcription"]))
print(text)
#tts(text)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)