You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Alexa虚拟助理时出现UnboundLocalError错误,如何修复?

错误根因

UnboundLocalError报错的核心原因是take_request()函数中的commands变量仅在try代码块内部完成赋值:

  • 语音识别流程中任意环节抛出异常(比如麦克风访问权限不足、Google语音识别服务连接失败、未检测到有效语音输入),都会触发except分支跳过commands的赋值逻辑
  • 最终函数return时找不到已赋值的commands变量,就会触发该错误
    你手动输入指令时无报错,是因为改用input输入不会触发语音相关的异常,commands必然能完成赋值;使用global关键字无效,是因为该问题本质是局部变量未初始化就返回,和全局作用域变量无关。
修复步骤
  1. 在take_request()函数开头给commands设置默认空值,保证无论try块是否正常执行,变量都有有效值
  2. 不要完全静默吞掉异常,增加异常打印逻辑方便后续排查问题
  3. 你代码中if "a" in commands仅做了打印操作,如果你是想做唤醒词判断,可以补充对应逻辑,否则不会影响命令返回,可按需保留或删除
修改后完整代码
import speech_recognition as sr
import pyttsx3
import datetime

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty('voice', voices[1].id)

def talk(text):
    engine.say(text)
    engine.runAndWait()

talk("Hi i'm Alexa ,your assistant")
talk("How can i help you ?")
print("Hi i'm Alexa")

def take_request():
    # 先给commands设置默认空值
    commands = ""
    try:
        with sr.Microphone() as source:
            talk("i am listening")
            print("listening ....")
            voice = listener.listen(source)
            command = listener.recognize_google(voice, language='en-us') # 可按需指定识别语言
            print(command)
            commands= command.lower()
            if "a" in commands:
                print(commands)
    except Exception as e:
        # 打印异常信息方便排查,不需要可注释
        print(f"识别出错: {e}")
    return commands

def run_alexa():
    cm = take_request()
    # 先判断返回值是否为空,避免空字符串判断报错
    if not cm:
        talk('Please say the command again.')
        print("pls talk again !!!")
        return
    if "play" in cm:
        print("playing music")
        talk("playing music")
    elif "time" in cm:
        time = datetime.datetime.now().strftime("%H:%M")
        print(time)
        talk("your current time is "+time)
    else:
        talk('Please say the command again.')
        print("pls talk again !!!")

while True:
    run_alexa()
补充说明

修改后如果出现识别出错的提示,可以根据报错内容排查对应问题:比如提示网络错误需要正常访问Google服务才能使用对应的语音识别能力,提示麦克风访问错误需要检查系统麦克风权限。
内容的提问来源于stack exchange,提问作者Phạm Tuấn Khải

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:15:01