Python 语音识别错误 - 通道数无效

Python speech recognition error - Invalid number of channels

作为项目的一部分,我正在 运行python 上编写语音识别代码。我面临着一个非常奇怪的问题 当我将语音识别代码放入如下函数时:

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))

它给我以下错误:

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

但是如果我 运行 相同的代码行在函数之外就像不在 def loop(): 里面一样 运行 是正确的

我该怎么办? 我的 python 版本是 3.5.4

频道是独享的吗?只有一个线程可以访问麦克风吗?您的问题可能是您试图同时多次访问麦克风(多次循环调用)而不是只访问一次(循环外)。

试试看:

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()

不要创建多个 Microphone() 实例。