语音助手程序未收到指令触发UnboundLocalError问题求助
语音助手UnboundLocalError问题修复方案
你的语音助手程序在提示“listening...”后3秒内未输入语音命令时,会触发UnboundLocalError导致崩溃。核心原因是take_command函数中command变量仅在try块内定义,当异常发生时(比如无语音输入),变量未被赋值就执行return,从而引发错误。
修复要点
- 提前初始化变量:在
take_command函数开头定义command为None,确保无论是否触发异常,变量都有初始值 - 精准捕获异常:避免使用裸
except,明确捕获语音识别相关的异常,方便排查问题 - 空值判断:在
run_alexa中先检查command是否有效,无效则直接跳过后续逻辑,避免空值引发其他错误
修改后的完整代码
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes listener = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty("voices") engine.setProperty("voice", voices[0].id) def talk(text): engine.say(text) engine.runAndWait() def take_command(): command = None # 提前初始化变量,避免未赋值就返回 try: with sr.Microphone() as source: print("listening...") # 设置超时时间(10秒无声音触发超时)和语音输入时长限制(最长5秒),可按需调整 voice = listener.listen(source, timeout=10, phrase_time_limit=5) command = listener.recognize_google(voice) if "computer" in command: command = command.replace("computer", "").strip() print(command) except sr.WaitTimeoutError: # 超时无语音输入时的提示 print("No voice input detected, waiting again...") except sr.UnknownValueError: # 无法识别语音时的反馈 talk("Sorry, I didn't catch that.") except Exception as e: # 其他异常的兜底处理 print(f"Error occurred: {e}") return command def run_alexa(): command = take_command() if not command: # 无有效命令时直接返回,跳过后续逻辑 return if "play" in command: song = command.replace("play", "").strip() talk(f"playing {song}") pywhatkit.playonyt(song) elif "time" in command: time = datetime.datetime.now().strftime("%I:%M %p") talk(f"the current time is {time}") elif "tell me about" in command: person = command.replace("tell me about", "").strip() try: info = wikipedia.summary(person, 1) talk(info) except wikipedia.exceptions.DisambiguationError: talk("There are multiple entries for that, please be more specific.") except wikipedia.exceptions.PageError: talk("I couldn't find information about that.") elif "your favourite artist" in command: talk("Mr worldwide aka pitbull") elif "joke" in command: talk(pyjokes.get_joke()) else: talk("what are you talking about willis") while True: run_alexa()
关键修改说明
- 给
take_command函数添加command = None初始化,彻底解决未赋值变量返回的问题 - 为
listener.listen设置超时参数,避免无限等待,同时明确异常类型处理 - 在字符串替换后添加
strip(),去除多余空格,提升命令识别准确性 - 给维基百科查询添加异常处理,避免查询不到内容时程序崩溃
- 在
run_alexa开头增加空值判断,无效命令直接跳过后续逻辑,减少不必要的执行
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

