Hey folks,
I've created this simple function that listens for voice commands:
def listen_for_command():
def callback(indata, frames, time, status):
threshold = 2
volume_norm = np.linalg.norm(indata) * 10
if volume_norm > threshold:
logging.info("Interrupt detected!")
stop_flag.set()
def background_noise_detector():
with sd.InputStream(callback=callback):
while not stop_flag.is_set():
pass
print("Background noise detection stopped")
noise_thread = threading.Thread(target=background_noise_detector, daemon=True)
noise_thread.start()
with source as s:
logging.info("Listening for commands...")
recognizer.adjust_for_ambient_noise(s, duration=0.8)
try:
audio = recognizer.listen(s, timeout=15, phrase_time_limit=12)
logging.info("Audio captured successfully.")
except sr.WaitTimeoutError:
print("No speech detected with 15 seconds")
return None
except Exception as e:
print(f"Error during listening: {e}")
return None
try:
logging.info("Using Whisper for offline transcription...")
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
f.write(audio.get_wav_data())
audio_array = whisper.load_audio(f.name)
command = model.transcribe(audio_array)["text"].strip().lower()
os.remove(f.name)
return command if is_valid_command(command) else None
except ...
I noticed that after it captures a command, whenever I speak to the microphone it waits until finishing playback & Interrupt detected! is only printed after it finishes. Is threshold wrong? Or I am doing a mistake?