如何使聊天机器人在呼叫其名称时开始侦听



我想让我的python聊天机器人在我说"Echo"时开始监听。我该怎么做?下面是聊天机器人的一个片段。

import speech_recognition as sr
running=True
r = sr.Recognizer()
def Speech():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1)
print("Say something!")
audio = r.listen(source)    
try:
x=r.recognize_google(audio)
print(x)
except sr.UnknownValueError:
pass
except sr.RequestError as e:
pass
while running==True:
r = sr.Recognizer()
with sr.Microphone() as source:
while 1:
Speech()

经过多次尝试,我做对了。但我发现它很慢。如果你有更好的策略,请评论。

import speech_recognition as sr
running=True
r = sr.Recognizer()
def Speech():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1)
print("Say something!")
audio = r.listen(source)    
try:
x=r.recognize_google(audio)
if x=="hello":
print("Speak up")
audio = r.listen(source)
print(r.recognize_google(audio))
except sr.UnknownValueError:
pass
except sr.RequestError as e:
pass
while running==True:
Speech()

最新更新