Continuously listen for speech in a background thread
The listen_in_background() method enables continuous speech recognition without blocking your main program. This is useful for voice-controlled applications, virtual assistants, and real-time transcription systems.
Continuously listens for speech from an audio source
Detects when a phrase starts and ends
Calls your callback function with each detected phrase
Runs independently of your main program thread
The background thread is a daemon thread, meaning it won’t prevent your program from exiting. You must keep the main thread alive if you want continuous listening.
import speech_recognition as srimport timedef callback(recognizer, audio): # Called from background thread when phrase is detected try: text = recognizer.recognize_google(audio) print(f"You said: {text}") except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print(f"Error: {e}")r = sr.Recognizer()m = sr.Microphone()# Start background listeningstop_listening = r.listen_in_background(m, callback)# Do other work while listening continuesfor i in range(60): time.sleep(1) print(f"Listening... {i+1}s")# Stop listeningstop_listening(wait_for_stop=True)
Here’s the complete background listening example from the library:
#!/usr/bin/env python3import timeimport speech_recognition as sr# Callback function runs in background threaddef callback(recognizer, audio): # Received audio data, now recognize it try: text = recognizer.recognize_google(audio) print("Google Speech Recognition thinks you said " + text) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results; {0}".format(e))# Create recognizer and microphoner = sr.Recognizer()m = sr.Microphone()# Calibrate for ambient noise (only need to do this once)with m as source: r.adjust_for_ambient_noise(source)# Start listening in backgroundstop_listening = r.listen_in_background(m, callback)# Do some unrelated work for 5 secondsfor _ in range(50): time.sleep(0.1)# Stop background listeningstop_listening(wait_for_stop=False)# Do more unrelated workwhile True: time.sleep(0.1)
import speech_recognition as srimport timefrom queue import Queue# Thread-safe queue for storing transcriptionstranscription_queue = Queue()def callback(recognizer, audio): try: text = recognizer.recognize_google(audio) # Put in queue instead of printing transcription_queue.put(text) except sr.UnknownValueError: passr = sr.Recognizer()m = sr.Microphone()with m as source: r.adjust_for_ambient_noise(source)stop_listening = r.listen_in_background(m, callback)# Process transcriptions from main threadfor _ in range(50): time.sleep(0.1) # Check for new transcriptions while not transcription_queue.empty(): text = transcription_queue.get() print(f"Transcribed: {text}") # Process the text safely in main threadstop_listening(wait_for_stop=True)
The stop_listening() function accepts one parameter:
# Stop immediately, don't wait for cleanupstop_listening(wait_for_stop=False)# Stop and wait for thread to finish (may take 1-2 seconds)stop_listening(wait_for_stop=True)
If using wait_for_stop=True, you must call it from the same thread that started background listening.
r.energy_threshold = 300 # Lower if neededprint(f"Energy threshold: {r.energy_threshold}")
Verify microphone is working:
import speech_recognition as srprint(sr.Microphone.list_working_microphones())
Test with regular listen() first:
with sr.Microphone() as source: audio = r.listen(source) print("Audio captured successfully")
Program exits immediately
The background thread is a daemon thread and won’t keep your program alive:
import timestop_listening = r.listen_in_background(m, callback)# Wrong - program exits immediately# (no code to keep it running)# Right - keep program alivewhile True: time.sleep(0.1)
High CPU usage
Background listening continuously polls audio. To reduce CPU usage: