Python语音助手

发布于 2025-01-16 11:48:09 字数 557 浏览 5 评论 0原文

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

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”

So i wrote this function to get what i say:

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

and then while True the function is running like this:

query = takeCommand().lower()

but i get this error:
local variable 'query' referenced before assignment

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2025-01-23 11:48:09

您的代码遇到异常情况并且未定义查询,请尝试以下操作:

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

Your code is running into the exception condition and not defining query try this:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文