Python 语音助手

Python voice assistant

所以我写了这个函数来得到我说的:

def takeCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.pause_threshold = 2
        audio = r.listen(source)
    try:   
        query = r.recognize_google(audio, language='en')

    except Exception as e:
        speak("Say that again please...")
        pass
    
    return query

然后当函数为 True 时 运行 如下所示:

query = takeCommand().lower()

但我收到此错误: 赋值前引用的局部变量'query'

您的代码 运行 进入异常条件并且未定义 query 试试这个:

def takeCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.pause_threshold = 2
        audio = r.listen(source)
    try:   
        query = r.recognize_google(audio, language='en')

    except Exception as e:
        speak("Say that again please...")
        return # NEW CODE
    
    return query