为什么这个pyaudio程序不产生声音?

时间:2019-03-21 00:22:17

标签: python pyaudio

我正在使用Anaconda提供的lubuntu 18.04,python 3.6.5和pyaudio 0.2.11,安装者:

  

conda安装nwani :: portaudio nwani :: pyaudio

我使用了nwani频道的pyaudio,因为他修复了一个错误。 查看讨论OSError: No Default Input Device Available

但是,我仍然在努力使一切正常工作。我从互联网尝试过的示例中大约有一半失败了。我会保持具体。有人可以看到为什么附加代码不直接从麦克风输出声音吗?

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

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

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()

0 个答案:

没有答案
相关问题