作为项目的一部分,我正在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行,在 初始化 self._stream = pa.open(* arguments)OSError:[Errno -9998]无效的通道数
但是如果我在函数外部运行相同的代码行,例如不在函数内部def loop():运行,
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()实例。
Microphone()