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

Python speech_recognition库listen()无短语时限阻塞问题求助

问题解决方法

核心原因

第二个recognizer.listen(source)阻塞是因为默认配置下,该方法会持续等待直到检测到语音结束后的静音时长超过pause_threshold,如果环境存在持续轻微噪音或未触发静音检测逻辑,就会一直卡住。同时,重复创建sr.Microphone()实例可能引发音频设备资源冲突,加重阻塞问题。

具体修复步骤

1. 复用麦克风实例

不在唤醒后重新初始化Microphone,全局复用同一个音频源,减少设备资源占用与冲突。

2. 调整静音检测阈值

通过recognizer.pause_threshold和recognizer.non_speaking_duration优化语音结束判断逻辑,避免无限等待:

  • pause_threshold:设置语音结束后需要保持静音的时长(单位:秒),达到该时长就判定语音结束
  • non_speaking_duration:允许的短暂非语音时长(比如呼吸、停顿),避免误判

3. 增加超时机制(不依赖phrase_time_limit)

给第二个listen()添加timeout参数,防止极端场景下持续阻塞,同时保留持续监听能力。

修复后的完整代码

import speech_recognition as sr

# 全局初始化识别器和麦克风,避免重复创建
recognizer = sr.Recognizer()
microphone = sr.Microphone()

# 调整静音检测参数,适配日常场景
recognizer.pause_threshold = 0.8
recognizer.non_speaking_duration = 0.5

if __name__ == "__main__":
    print("Initialize Jarvis......")

    while True:
        try:
            with microphone as source:
                # 每次监听前校准环境噪音,提升判断准确性
                recognizer.adjust_for_ambient_noise(source, duration=0.5)
                print("\nListening for wake word...")
                audio = recognizer.listen(source, timeout=2, phrase_time_limit=2)

            wake_word = recognizer.recognize_google(audio).lower()

            if wake_word == "jarvis":
                print("Wake word detected!")

                with microphone as source:
                    recognizer.adjust_for_ambient_noise(source, duration=0.3)
                    print("\nListening for command...")
                    # 设置超时防止无限阻塞,靠pause_threshold判断语音结束
                    audio = recognizer.listen(source, timeout=10)
                    command = recognizer.recognize_google(audio).lower()
                    print(f"Received command: {command}")

        except sr.WaitTimeoutError:
            # 超时属于正常场景,跳过错误打印
            continue
        except Exception as x:
            print(f"Error : {x}")

额外优化建议

  • 每次监听前调用adjust_for_ambient_noise,动态适配环境噪音,提升识别准确率和结束判断的准确性。
  • 单独捕获sr.WaitTimeoutError,避免将正常超时打印为错误信息,让日志更清晰。

内容的提问来源于stack exchange,提问作者Sandip Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 21:56:05