【问题标题】:Python speech recognition error - Invalid number of channelsPython语音识别错误 - 通道数无效
【发布时间】:2018-06-21 01:26:11
【问题描述】:

作为项目的一部分,我正在 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))

它给了我以下错误:

以 sr.Microphone(device_index=2) 作为来源:文件“/usr/local/lib/python3.5/dist-packages/speech_recognition/init.py”, 第 141 行,在 输入 input=True, #stream 是一个输入流 File "/usr/local/lib/python3.5/dist-packages/pyaudio.py", line 750, in open 流 = 流(self,*args,**kwargs)文件“/usr/local/lib/python3.5/dist-packages/pyaudio.py”,第 441 行,在 初始化 self._stream = pa.open(**arguments) OSError: [Errno -9998] 通道数无效

但是,如果我在函数外部运行相同的代码行,而不是在 def loop(): 内部运行,它会正常运行

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

【问题讨论】:

  • 删除 device_index 使它对我有用with sr.Microphone() as source:
  • 它可以正常工作,但卡在r.listen(audio) 我找不到有效的解决方案
  • 你必须在“说点什么”提示下说点什么,否则会卡住

标签: python python-3.x speech-recognition


【解决方案1】:

试试这个方法:

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() 实例。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我明白了...那我该如何解决呢?因为此错误仅在我传递“device_index=2”参数时发生。没有该参数,错误不存在,但这会导致一系列新问题,例如卡在r.listen(audio)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多