2

I am using the SpeechRecognition Python package to get the audio from the user.

import speech_recognition as sr
# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
    print("Say something!")
    audio = r.listen(source)

This piece of code when executed starts listening for the audio input from the user. If the user does not speak for a while it automatically stops.

  • I want to know how can we get to know that it has stopped listening to audio?
  • How can I manually disable it ? I mean if i want to listen audio for 50 seconds and then stop listening to any further audio?
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
indexOutOfBounds
  • 541
  • 7
  • 27

3 Answers3

4
  1. as the documentation specifies, recording stops when you exit out of with. you may print something after with to know that the recording has been stopped.
  2. here's how you can stop recording after 50 seconds.
import speech_recognition as sr 
recognizer = sr.Recognizer() 
mic = sr.Microphone(device_index=1) 
with mic as source:
    recognizer.adjust_for_ambient_noise(source)
    captured_audio = recognizer.record(source=mic, duration=50)
Naveen Reddy Marthala
  • 2,622
  • 4
  • 35
  • 67
2

I think you need to read the library specifications; then, you can check that using record method instead of listen method is preferable to your application.

LlaveLuis
  • 88
  • 2
  • 5
1

Late and not a direct answer, but to continuously record the microphone until the letter q is pressed, you can use:

import speech_recognition as sr
from time import sleep
import keyboard # pip install keyboard

go = 1

def quit():
    global go
    print("q pressed, exiting...")
    go = 0

keyboard.on_press_key("q", lambda _:quit()) # press q to quit

r = sr.Recognizer()
mic = sr.Microphone()
print(sr.Microphone.list_microphone_names())

mic = sr.Microphone(device_index=1)


while go:
    try:
        sleep(0.01)
        with mic as source:
            audio = r.listen(source)
            print(r.recognize_google(audio))
    except:
        pass
    
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • on my macbook i need to us `sudo` to start this script, unless `keyboard` library bug it. `sudo python3 stack.py` – oruchkin Jun 22 '22 at 20:18