首页 文章

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

提问于
浏览
0

我在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是一个输入流文件“/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]无效的通道数

但是如果我在函数外部运行相同的代码行,就像在 def loop(): 内运行一样,它运行正常

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

2 回答

  • 0

    试试这个:

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

  • 3

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

相关问题