简体   繁体   English

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

[英]Python speech recognition error - Invalid number of channels

I'm running a speech recognition code on python as part of a project. 作为项目的一部分,我正在python上运行语音识别代码。 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 以sr.Microphone(device_index = 2)作为源:文件“ /usr/local/lib/python3.5/dist-packages/speech_recognition/ init .py”,第141行,在输入 input = True中,#stream是输入流文件“ /usr/local/lib/python3.5/dist-packages/pyaudio.py”,第750行,在开放流中= Stream(self,* args,** kwargs)文件“ / usr / local / lib / python3.5 / dist-packages / pyaudio.py“,第441行, init self._stream = pa.open(** arguments)OSError:[Errno -9998]无效的通道数

But if I run the same lines of code outside the function like not inside the def loop(): it runs properly 但是,如果我在函数外部运行相同的代码行,例如不在def loop():内部运行def loop():它可以正常运行

What should I do? 我该怎么办? My python version is 3.5.4 我的python版本是3.5.4

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. 不要创建多个Microphone()实例。

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). 您的问题可能是您尝试同时(多次循环调用)多次访问麦克风,而不是一次(循环外)访问麦克风。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM