我转到另一个功能后,我的麦克风又回去听了

时间:2018-05-19 18:01:51

标签: python

每当我运行此代码并告诉启动函数“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)   

代码将返回with sr.Mirophone as source的Listen() 这就是我调用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))

1 个答案:

答案 0 :(得分:2)

phrase_time_limit函数内调用listen方法时,需要指定一个函数参数Google
phrase_time_limit表示程序的等待时间,等待用户提供输入的秒数。在这里等待2秒钟。如果您没有给出任何时间限制,它将无限期地等待。

从源代码文档:

  

phrase_time_limit参数是最大秒数   这将允许一个短语在停止之前继续   返回在时间限制之前处理的短语部分   到达。结果音频将是当时截止的短语   限制。如果phrase_timeoutNone,则不会有短语时间   限制。

澄清timeout参数

  

timeout参数是此参数的最大秒数   在放弃投掷之前会等待一个短语开始   speech_recognition.WaitTimeoutError例外。如果是timeout   None,没有等待超时。

有关详细信息,请查看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)

这次改变之后,它对我有用 检查是否是 with sr.Microphone() as source:没有 with sr.Microphone as source:。你错过了大括号。