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

Python语音识别后台监听时回调函数未触发问题求助

后台音频监听回调函数未触发问题排查与解决

问题描述

尝试实现脚本运行时的后台音频监听,运行代码后仅持续打印gone,回调函数中的go和fun trig从未输出,说明回调未被触发。相关代码如下:

import cv2
import mediapipe as mp
import pyautogui
import speech_recognition as sr
import time
r = sr.Recognizer()
m = sr.Microphone()
def callback(recognizer, audio):
    print('go')
    # received audio data, now we'll recognize it using Google Speech Recognition
    try:
        print("fun trig")

        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))


r = sr.Recognizer()
m = sr.Microphone()
# print(sr.Microphone.list_microphone_names())
with m as source:
    r.adjust_for_ambient_noise(source)  # we only need to calibrate once, before we start listening

# start listening in the background (note that we don't have to do this inside a `with` statement)
stop_listening = r.listen_in_background(m, callback)
# `stop_listening` is now a function that, when called, stops background listening

# do some unrelated computations for 5 seconds
for _ in range(50): time.sleep(0.1)   # we're still listening even though the main thread is doing other things

# calling this function requests that the background listener stop listening
stop_listening(wait_for_stop=False)

# do some more unrelated things
while True: 
    print('gone') 
    time.sleep(0.1)

问题原因

  1. 重复初始化对象:代码中先后两次初始化sr.Recognizer()和sr.Microphone(),导致用于环境噪音校准的对象和后续启动后台监听的对象不是同一个,校准参数无法生效。
  2. 监听停止过早:5秒的循环结束后立即调用stop_listening停止监听,后续的while True循环已经没有后台监听在运行,自然不会触发回调。
  3. 噪音校准可能过度:默认的adjust_for_ambient_noise校准时长较短,可能导致识别阈值过高,轻微的语音无法触发回调。

解决方案

1. 移除重复的对象初始化

删除代码中第二次的r = sr.Recognizer()和m = sr.Microphone(),确保全程使用同一个识别器和麦克风对象。

2. 调整监听停止时机

如果需要在后续的while True循环中保持监听,不要提前调用stop_listening;如果确实需要在某个时机停止,确保停止前有足够的时间触发语音识别。

3. 优化噪音校准参数

延长噪音校准的时长,让识别器更准确地判断环境噪音水平,比如:

with m as source:
    r.adjust_for_ambient_noise(source, duration=1)  # 校准时长设为1秒

修正后的完整代码

import cv2
import mediapipe as mp
import pyautogui
import speech_recognition as sr
import time

# 只初始化一次识别器和麦克风
r = sr.Recognizer()
m = sr.Microphone()

def callback(recognizer, audio):
    print('go')
    try:
        print("fun trig")
        text = recognizer.recognize_google(audio)
        print(f"Google Speech Recognition thinks you said {text}")
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")

# 校准环境噪音,延长校准时长
with m as source:
    r.adjust_for_ambient_noise(source, duration=1)

# 启动后台监听
stop_listening = r.listen_in_background(m, callback)

# 执行无关操作的同时保持监听
for _ in range(50):
    time.sleep(0.1)

# 若不需要停止监听,注释掉下面这行
# stop_listening(wait_for_stop=False)

# 持续运行并保持监听
while True:
    print('gone')
    time.sleep(0.1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:45:19