#๐Ÿ”’ Discovering `sounddevice`, `speechrecognition` and numpy

4 messages ยท Page 1 of 1 (latest)

rare brook
#

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?

robust lotusBOT
#

@rare brook

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

robust lotusBOT
#

@rare brook

Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.