Python语音识别控制自制浏览器时遇UnboundLocalError求助
解决语音识别函数的UnboundLocalError问题
我用Python开发了一款网页浏览器,想通过语音识别实现控制(比如打开/关闭标签页、输入URL),但调用语音识别类的take_command()方法时,遇到了UnboundLocalError: local variable 'command' referenced before assignment错误。我的语音识别代码如下:
import speech_recognition as sr listener = sr.Recognizer() class VoiceRecognition(): def take_command(self): try: while True: with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) command = command.lower() print(command) except: pass return command
错误原因
command变量仅在try块内的while循环中定义,一旦出现异常(比如麦克风输入故障、Google语音识别失败),循环未执行到赋值语句就跳出,command会处于未定义状态,最终return时触发错误。- 原代码中的
while True是死循环,即使识别到有效命令也不会退出,永远无法执行到return语句,只有发生异常时才会走到return,但此时command未被赋值。
修复后的代码
import speech_recognition as sr listener = sr.Recognizer() class VoiceRecognition(): def take_command(self): # 提前初始化变量,避免未定义的情况 command = None try: with sr.Microphone() as source: print('listening...') # 处理环境噪音,提升识别准确率 listener.adjust_for_ambient_noise(source, duration=0.5) # 设置监听超时和短语时长限制,避免无限等待 voice = listener.listen(source, timeout=5, phrase_time_limit=5) command = listener.recognize_google(voice) command = command.lower() print(command) except sr.UnknownValueError: print("无法识别语音,请重新说一遍") except sr.RequestError: print("语音识别服务请求失败,请检查网络") except Exception as e: print(f"发生未知错误:{e}") return command
关键修改说明
- 提前初始化
command = None,确保无论是否发生异常,return时变量都已定义。 - 移除死循环,改为单次监听(如果需要持续监听,建议在外部调用时实现循环逻辑,更灵活)。
- 添加环境噪音处理、超时限制,优化识别体验。
- 捕获具体异常类型,替代裸
except,便于定位问题并给出明确提示。
持续监听的调用示例
如果需要持续接收语音命令控制浏览器,可以这样调用:
vr = VoiceRecognition() while True: cmd = vr.take_command() if cmd: # 根据识别到的命令执行对应操作 if "打开标签页" in cmd: # 这里写打开标签页的代码 print("执行打开标签页操作") elif "关闭标签页" in cmd: # 这里写关闭标签页的代码 print("执行关闭标签页操作") elif "输入url" in cmd: # 这里写输入URL的代码 print("执行输入URL操作")
内容的提问来源于stack exchange,提问作者Lahiru Tharaka
相关产品推荐
相关产品推荐

