问题
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
回答1:
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.
回答2:
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).
来源:https://stackoverflow.com/questions/50952667/python-speech-recognition-error-invalid-number-of-channels