1
votes

I'm running a speech recognition code on python as part of a project. I'm facing a really odd kind of a problem When I put the speech recognition code inside a function like:

def loop():
    r=sr.Recognizer()
    with sr.Microphone(device_index=2) as source:
            print("say something")
            audio = r.listen(source)
            try:
                    print("you said "+r.recognize_google(audio))
            except sr.UnknownValueError:
                    print("Could not understand")
            except sr.RequestError as e:
                    print("errpr: {0}".format(e))

It gives me the following error:

with sr.Microphone(device_index=2) as source: File "/usr/local/lib/python3.5/dist-packages/speech_recognition/init.py", line 141, in enter input=True, # stream is an input stream File "/usr/local/lib/python3.5/dist-packages/pyaudio.py", line 750, in open stream = Stream(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/pyaudio.py", line 441, in init self._stream = pa.open(**arguments) OSError: [Errno -9998] Invalid number of channels

But if I run the same lines of code outside the function like not inside the def loop(): it runs properly

What should I do? My python version is 3.5.4

2
removing the device_index made it work for me with sr.Microphone() as source:ClumsyPuffin
It works without error but it gets stuck at r.listen(audio) for which I couldn't find solutions that workedRishiC
you have to speak something at the "say something" prompt or else it will be stuckClumsyPuffin

2 Answers

3
votes

Try that way:

r = sr.Recognizer()
m = sr.Microphone(device_index=2)

def loop():
    with m as source:
        print("say something")
        audio = r.listen(source)
        try:
            print("you said "+r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Could not understand")
        except sr.RequestError as e:
            print("errpr: {0}".format(e))

loop()

Don't create multiple Microphone() instances.

0
votes

Is access to the channel exclusive? Can only one thread hold access to the microphone? Your problem might be that you are trying to access the microphone multiple times concurrently (multiple loop calls) rather than just access it once (outside of loop).