我已经发布了下面的完整代码,我希望能够实现audio = r.listen(source)
的重复执行。我已经得到了重复的代码,但它每次都返回相同的东西。我真的不喜欢放弃,来这里寻求答案(第一次发帖(。每次执行do_again(quit)
函数时,我必须做些什么才能让代码返回新短语。基本上,程序要求说些什么,第一次就很好。当我被提示继续或退出时,我输入"c",我想重复整个过程。如有任何帮助,我们将不胜感激。附言:我是python的新手,可能做这件事完全错了。任何提示也将不胜感激!
这是代码(欢迎所有批评。比如:有更好的更干净的方法吗?(
import speech_recognition as sr
import sys
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
print('Speak clearly for better results ...')
audio = r.listen(source)
quit = 'c'
q = quit
def do_again(quit):
quit = input('Press c to continue OR press q to quit: ')
q = quit
if q == 'q':
print('Exiting program')
sys.exit()
elif q == 'c':
print('Running again...')
else:
print('ERROR! Press c to continue OR press q to quit ')
return q
response = {"success": True,
"error": None,
"transcription": None
}
while q == 'c':
try:
# I want this to return new phrase instead of returning the same phrase.
response['transcription'] = r.recognize_sphinx(audio) # I want a new 'response' here
print(f"[SPEECH RECOGNIZED] {response['transcription']}")
except sr.UnknownValueError:
print(f"[FATAL ERROR] Exiting...")
except sr.RequestError as e:
response['success'] = False
response['error'] = 'API Unavailable/unresponsive'
print(f"[FATAL ERROR] {response['error']} {e}")
do_again(quit)
我想我找到了答案。我正在阅读带有help(r.Recognizer)
功能的python解释器中的文档。我找到了一个listen_in_background
方法。listen_in_background
能满足我的需求吗?我知道这是一个愚蠢的计划,但我计划为自己做一些实际的事情。如果这能奏效,你们可以关闭这个线程。我觉得自己很笨哈哈。我会尝试一下,如果效果不好,发布我的解决方案。再次感谢!
[编辑]成功了!我定义了这个函数:def callback(r,audio)
,它是stop_listening = r.listen_in_background(m, callback)
所需要的。我很难理解这条线路的用途:stop_listening(wait_for_stop=True)
。如果有人能解释一下,这样我将来可以更好地使用它。最后,我添加了一个"魔法词"来退出程序(只需说"退出",sys.quit()
就会终止程序(。有更好的方法吗?
这是新代码:
import time
import speech_recognition as sr
import sys
def callback(r, audio):
global done
try:
print(f"[PocketSphinx]: Thinks you said: '{r.recognize_sphinx(audio)}'. Read some more ")
except sr.UnknownValueError:
print(f"[PocketSphinx]: Fatal error! Unknown Value Error! Exiting program.")
except sr.RequestError as ex:
print(f"[PocketSphinx]: Fatal error! Could not process request! {ex}")
if r.recognize_sphinx(audio) == 'quit':
print(f"[PocketSphinx]: You said the magic word: 'quit'... Exiting program.")
done = True
r = sr.Recognizer()
r.energy_threshold = 4000
m = sr.Microphone()
done = False
with m as source:
r.adjust_for_ambient_noise(source)
print(f"[PocketSphinx]: Read to me... Say 'quit' to exit...")
stop_listening = r.listen_in_background(m, callback)
# 5 second delay
for _ in range(50):
time.sleep(0.1)
while not done:
time.sleep(0.1)
if done:
stop_listening(wait_for_stop=True)
sys.exit()