You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python语音识别程序无法接收语音命令的报错排查求助

Python语音识别程序报错分析与解决

报错原因

  1. 麦克风初始化失败:sr.Microphone()实例化时未能成功打开音频流(source.stream为None),导致调用r.listen(source)触发断言错误。常见诱因包括:
    • 系统未授予程序麦克风访问权限
    • 未正确安装依赖库pyaudio(speech_recognition依赖它处理音频输入)
    • 系统默认麦克风设备不可用或无法被识别
  2. 异常处理连锁错误:原代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:07:41