PyAudio error: [Errno -9986] Could not get stream information

PyAudio error: [Errno -9986] Could not get stream information

我从 PyAudio 文档中获取了电线示例的修改版本:

    def mic_to_vac_pipe(self):
        microphone_input_stream = self.pyaudio.open(
            format=self.pyaudio.get_format_from_width(2),
            channels=1,
            rate=self.RATE,
            input=True,
            output=True,
            input_device_index=1,
            frames_per_buffer=self.CHUNK_SIZE
        )

        cable_output_stream = self.pyaudio.open(
            format=self.pyaudio.get_format_from_width(2),
            channels=1,
            rate=self.RATE,
            output=True,
            output_device_index=5, # change to 8
            frames_per_buffer=self.CHUNK_SIZE
        )

        # This will last for 217483647 seconds, or 68.09 years
        for i in range(0, int(self.RATE / self.CHUNK_SIZE * 2147483647)):
            data = microphone_input_stream.read(self.CHUNK_SIZE)
            cable_output_stream.write(data, self.CHUNK_SIZE)

        microphone_input_stream.stop_stream()
        microphone_input_stream.close()
        cable_output_stream.stop_stream()
        cable_output_stream.close()

这曾经有效,直到我将其移至 class,现在我收到此错误:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\pwill\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
    self.run()
  File "C:\Users\pwill\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "d:\documents\coding\python\kyan\kyan\kyan.py", line 49, in mic_to_vac_pipe
    microphone_input_stream = self.pyaudio.open(
  File "C:\Users\pwill\AppData\Local\Programs\Python\Python39\lib\site-packages\pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "C:\Users\pwill\AppData\Local\Programs\Python\Python39\lib\site-packages\pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9986] Could not get stream information

我在使用 self.pyaudio.get_host_api_info_by_index(0) (OSError: [Errno -9978] Invalid host api info) 时也遇到了类似的错误。这些错误是否可能相关?

我怀疑它可能在内部与 PortAudio 有关,因为绕过 get_host_api_info_by_index(0) 调用(它用于获取音频设备的数量,因此我可以通过为设备计数设置硬编码数字来绕过)告诉我认为 PortAudio 没有被初始化,即使 PyAudio 被初始化,它也同时初始化了 PortAudio。 我该如何解决这个问题?

我想通了! 我的问题是 class 的 __init__ 函数中的 pyaudio.terminate()。当我将它添加到 class 时它停止工作的唯一原因是因为我还将它添加到一个单独的线程,这涉及调用 thread.join(),这会阻塞 terminate()。将这个 terminate() 函数移动到正确的位置解决了我的问题。