语音识别项目麦克风源报错:AudioSource断言及NoneType属性错误
语音识别监听功能报错解决方法
运行语音监听代码时出现AssertionError和AttributeError,即使手动指定麦克风设备索引为1仍未解决。相关代码及报错如下:
import speech_recognition as sr robot_ear = sr.Recognizer() with sr.Microphone(device_index=1) as mic: #robot_ear.adjust_for_ambient_noise(mic) print("Robot: I'm listening") audio = robot_ear.listen(mic) try: you = robot_ear.recognize_google(audio) except: you = "" print(you)
报错信息:
Robot: I'm listening Traceback (most recent call last): File "C:\Users\trung\Documents\Python 3\nghe.py", line 7, in <module> audio = robot_ear.listen(mic) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\trung\AppData\Local\Programs\Python\Python311\Lib\site-packages\speech_recognition\__init__.py", line 465, in listen assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?" ^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\trung\Documents\Python 3\nghe.py", line 4, in <module> with sr.Microphone(device_index=1) as mic: File "C:\Users\trung\AppData\Local\Programs\Python\Python311\Lib\site-packages\speech_recognition\__init__.py", line 189, in __exit__ self.stream.close() ^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'close'
核心原因
麦克风设备初始化失败,导致Microphone对象的stream属性为None。可能的触发因素:
- 指定的设备索引1并非实际可用的麦克风设备
- 程序没有麦克风访问权限
- 麦克风硬件被其他程序占用
解决步骤
- 步骤1:确认正确的麦克风设备索引
运行以下代码列出所有可用音频输入设备,找到对应麦克风的正确索引:
import speech_recognition as sr for index, name in enumerate(sr.Microphone.list_microphone_names()): print(f"设备索引 {index}: {name}")
步骤2:检查麦克风权限
在Windows设置中,确保Python程序拥有麦克风访问权限:- 打开「设置」→「隐私和安全性」→「麦克风」
- 开启「允许应用访问麦克风」,并确保Python在列表中被允许
步骤3:修复代码结构并处理异常
将识别逻辑放到with块内部,同时捕获麦克风初始化异常,避免未定义变量和退出时的报错:
import speech_recognition as sr robot_ear = sr.Recognizer() try: with sr.Microphone(device_index=你的正确索引) as mic: robot_ear.adjust_for_ambient_noise(mic) # 建议开启,优化识别效果 print("Robot: I'm listening") audio = robot_ear.listen(mic) try: you = robot_ear.recognize_google(audio) except sr.UnknownValueError: you = "没听清你说的什么" except sr.RequestError: you = "无法连接到语音识别服务" print(you) except OSError: print("无法初始化麦克风,请检查设备索引或权限")
内容的提问来源于stack exchange,提问作者Nghia Nguyen
相关产品推荐
相关产品推荐

