语音助手遇背景噪音时类型异常致崩溃的问题求助
问题原因
当只有背景噪音无有效语音时,listener.recognize_google(voice, show_all=True)返回的actual_result不再是包含alternative键的字典,而是列表(或空结构)。后续代码直接以字典方式访问actual_result["alternative"],触发TypeError。
解决方案
修改take_command函数,增加对actual_result类型和有效性的校验,过滤无意义输入后重新监听,直到获取有效语音命令:
import PIL import speech_recognition as sr import pyttsx3 import random import time listener = sr.Recognizer() engine = pyttsx3.init() def talk(text): try: print("Assistant - " + text.capitalize()) engine.say(text) engine.runAndWait() except ValueError: pass def take_command(): try: with sr.Microphone() as source: # 校准环境噪音,减少误识别 listener.adjust_for_ambient_noise(source, duration=0.5) voice = listener.listen(source) actual_result = listener.recognize_google(voice, show_all=True) # 校验结果有效性:必须是字典且包含alternative键 if not isinstance(actual_result, dict) or "alternative" not in actual_result: return take_command() alternatives = actual_result["alternative"] # 确保alternatives是有效列表 if not isinstance(alternatives, list) or len(alternatives) == 0: return take_command() # 选择最优识别结果 if any("confidence" in alt for alt in alternatives): best_hypothesis = max(alternatives, key=lambda alt: alt.get("confidence", 0)) else: best_hypothesis = alternatives[0] # 确保存在有效转录文本 if "transcript" not in best_hypothesis: return take_command() command = best_hypothesis["transcript"].lower().replace('alexa', '') # 过滤空命令 if not command.strip(): return take_command() print("\nUser - " + command.capitalize()) return command # 捕获语音识别相关异常:无语音、API请求失败等 except (sr.UnknownValueError, sr.RequestError, TypeError, ValueError): return take_command()
关键修改说明
- 增加
listener.adjust_for_ambient_noise:提前校准环境噪音,降低误识别概率 - 多层有效性校验:依次检查结果类型、
alternative字段、列表有效性、转录文本存在性 - 过滤空命令:排除纯空格等无意义输入
- 扩展异常捕获:覆盖语音识别过程中常见的错误类型,确保程序稳定重试
内容的提问来源于stack exchange,提问作者Nir Malka
相关产品推荐
相关产品推荐

