Python语音识别程序无法接收语音命令的报错排查求助
Python语音识别程序报错分析与解决
报错原因
- 麦克风初始化失败:
sr.Microphone()实例化时未能成功打开音频流(source.stream为None),导致调用r.listen(source)触发断言错误。常见诱因包括:- 系统未授予程序麦克风访问权限
- 未正确安装依赖库
pyaudio(speech_recognition依赖它处理音频输入) - 系统默认麦克风设备不可用或无法被识别
- 异常处理连锁错误:原代码中
try-except仅包裹了recognize_google部分,当r.listen()抛出错误后,with语句块退出时尝试关闭未初始化的stream,进而触发AttributeError。
解决方法
步骤1:确保依赖库正确安装
执行以下命令安装/更新依赖:
pip install --upgrade speechrecognition pyaudio
注意:如果安装pyaudio失败,Windows用户可下载对应Python版本的whl文件手动安装
步骤2:检查麦克风权限
- Windows:进入「设置-隐私和安全性-麦克风」,确保你的Python IDE(如PyCharm)被允许访问麦克风
- 重启IDE后再运行程序
步骤3:修改代码结构,完善异常处理
调整take_command函数,将with块内的操作整体包裹在try-except中,同时添加环境噪音校准优化识别效果:
import speech_recognition as sr import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") def say(text): print("Speaking......") speaker.Speak(text) def take_command(): r = sr.Recognizer() try: with sr.Microphone() as source: print("Adjusting for ambient noise...") r.adjust_for_ambient_noise(source, duration=1) r.pause_threshold = 1 print("Listening now...") audio = r.listen(source) query = r.recognize_google(audio, language='en-in') print(f"User said: {query}") return query except sr.RequestError: return "Sorry, I can't access the speech recognition service right now." except sr.UnknownValueError: return "Sorry, I didn't catch that." except Exception as e: print(f"Error: {e}") return "Sorry, there was an issue with the microphone." if __name__ == '__main__': say("Hello, I am Jarvis A.I.") while True: print("Listening....") text = take_command() say(text)
可选:指定麦克风设备
如果系统有多个麦克风,可先列出所有设备再手动指定:
# 列出所有麦克风设备 for index, name in enumerate(sr.Microphone.list_microphone_names()): print(f"Microphone {index}: {name}") # 初始化时指定设备索引 with sr.Microphone(device_index=0) as source: # 后续操作不变
内容的提问来源于stack exchange,提问作者Abhinav Singh
相关产品推荐
相关产品推荐

