首页 > 解决方案 > 为什么这个 pyaudio 程序不产生任何声音?

问题描述

我正在使用 Anaconda 安装的 lubuntu 18.04、python 3.6.5 和 pyaudio 0.2.11:

康达安装 nwani::portaudio nwani::pyaudio

我使用 nwani 频道中的 pyaudio,因为他修复了一个错误。请参阅讨论OSError:没有可用的默认输入设备

但是,我仍然很难让任何东西正常工作。我从互联网上尝试过的示例中约有一半失败了。我会保持细节。任何人都可以看到为什么附加的代码不直接从麦克风输出声音吗?

调试打印,将“循环”连续写入控制台,生成器正在生成大小正确的字节数组,但仍然没有发出声音。

我确实知道生成器代码中的某些东西正在停止发出音频。我通过将音频数据从波形文件发送到生成器循环内的输出流来确定这一点 - 它不会发出。但是,如果我将生成器更改为:

if True: yield 1

从而导致生成器循环连续运行,但不执行任何缓冲区操作,发出波形文件。

完整程序:

import pyaudio
from six.moves import queue

# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms


class MicrophoneStream(object):
    """Opens a recording stream as a generator yielding the audio chunks."""
    def __init__(self, rate, chunk, audio):
        self._rate = rate
        self._chunk = chunk
        self._audio_interface = audio

        # Create a thread-safe buffer of audio data
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            channels=1, rate=self._rate,
            input=True, frames_per_buffer=self._chunk,
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self

    def __exit__(self, type, value, traceback):
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)
        self._audio_interface.terminate()

    def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
        """Continuously collect data from the audio stream, into the buffer."""
        self._buff.put(in_data)
        return None, pyaudio.paContinue

    def generator(self):
        while not self.closed:
            # Use a blocking get() to ensure there's at least one chunk of
            # data, and stop iteration if the chunk is None, indicating the
            # end of the audio stream.
            chunk = self._buff.get()
            if chunk is None:
                return
            data = [chunk]

            # Now consume whatever other data's still buffered.
            while True:
                try:
                    chunk = self._buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break

            yield b''.join(data)


p = pyaudio.PyAudio()

outputStream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True)

with MicrophoneStream(RATE, CHUNK, p) as inputStream:
    for data in inputStream.generator():
        outputStream.write(data)
        print('looping')


outputStream.stop_stream()
outputStream.close()
p.terminate()

标签: pythonpyaudio

解决方案


推荐阅读