每当我运行此代码并告诉启动函数“google”时,它都会返回到另一个函数。我已经尝试这样做了几天了,但仍然没有成功。任何帮助将不胜感激:)
import webbrowser
import string
import time
import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init()
r = sr.Recognizer()
def Listen():
with sr.Microphone() as sourceL:
print("Listening...")
Open = r.listen(sourceL, phrase_time_limit=2)
try:
if "Nova" in r.recognize_google(Open):
print("Nova Recieved...")
Command()
else:
Listen()
except:
Listen()
def Google():
print("what would you like me to search for you? ")
engine.say("what would you like me to search for you? ")
engine.runAndWait()
with sr.Microphone as source:
Search = r.listen(source)
Search = r.recognize(Search)
代码将返回到 处的 Listen(),以 sr.Mirophone 作为源
这就是我调用 google() 的方式...
def Command():
print("You called me?")
engine.say("you called me? ")
engine.runAndWait()
Cr = sr.Recognizer()
with sr.Microphone() as source:
print("Listening For Command...")
CommandToDo = Cr.listen(source, phrase_time_limit=2)
print("...")
if "YouTube" in Cr.recognize_google(CommandToDo):
YouTube()
elif "Google" in Cr.recognize_google(CommandToDo):
Google()
else:
print("Command not recognized>> " + r.recognize_google(CommandToDo))
最佳答案
在 Google
函数内调用 listen
方法时,您需要指定一个函数参数 phrase_time_limit
。
phrase_time_limit
表示程序的等待时间,即等待用户输入的秒数。这里会等待2秒。如果您不给出任何时间限制,它将无限期地等待。
来自源代码文档:
The
phrase_time_limit
parameter is the maximum number of seconds that this will allow a phrase to continue before stopping and returning the part of the phrase processed before the time limit was reached. The resulting audio will be the phrase cut off at the time limit. Ifphrase_timeout
isNone
, there will be no phrase time limit.
澄清超时
参数
The
timeout
parameter is the maximum number of seconds that this will wait for a phrase to start before giving up and throwing anspeech_recognition.WaitTimeoutError
exception. Iftimeout
isNone
, there will be no wait timeout.
更多详情请查看the source code.
def Google():
print("what would you like me to search for you? ")
engine.say("what would you like me to search for you? ")
engine.runAndWait()
with sr.Microphone() as source:
Search = r.listen(source, phrase_time_limit=2) # <-- Here
Search = r.recognize_google(Search)
print(Search)
经过此更改,它对我有用。
检查一下是
以 sr.Microphone() 作为源:
不
以 sr.Microphone 作为源:
。你错过了大括号。
关于python - 当我转到另一个功能后,我的麦克风会恢复监听状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428100/