首页 > 解决方案 > 尝试在同一设备上录制和播放时 PyAudio 无法正常工作

问题描述

我试图通过连接音频设备的输出来记录一些数据,将其通过吉他踏板,然后返回到同一音频设备上的线路中。

在 pyAudio 中,我可以毫无问题地输出到设备,但是当我打开 2 个流(输入/输出)或 1 个同时输入/输出的流时,pyaudio 停止工作。当我监控音频设备并且 stream.is_active 始终返回 true 时,我没有听到任何输出

我的代码:

from synthesizer import Player, Synthesizer, Waveform
import numpy as np
import time

BITRATE = 44100     #number of frames per second/frameset.  
CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
SAMPLE_LENGTH = 5

# open audio device
py_audio = pyaudio.PyAudio()

# generate audio
synthesizer = Synthesizer(osc1_waveform=Waveform.square, osc1_volume=1.0, use_osc2=False, rate=BITRATE)
out_wave = synthesizer.generate_constant_wave(440.0, SAMPLE_LENGTH)

def stream_callback(wave, frame):
    audio_data = (wave * float(2 ** 15 - 1)).astype(np.int16).tobytes()
    index = 0

    def callback(in_data, frame_count, time_info, status):
        nonlocal audio_data
        nonlocal index
        nonlocal frame

        print("got data!")
        frame.append(in_data)
        data_length = frame_count * CHANNELS * 2
        data = audio_data[index:(index+data_length)]
        index += data_length

        return (data, pyaudio.paContinue)

    return callback


frame_data = []


stream_options = {
    "format": FORMAT,
    "channels": CHANNELS,
    "rate": BITRATE,
    "output_device_index": 7,
    "input_device_index": 2,
    "output": True,
    "input": True,
    "stream_callback": stream_callback(out_wave, frame_data)
}

# Open Streams
stream_out = py_audio.open(**stream_options)

stream_out.start_stream()

# wait for stream to finish (5)
while stream_out.is_active():
    time.sleep(0.1)

print("Done!")


stream_out.stop_stream()
stream_out.close()


py_audio.terminate()

标签: pythonpyaudio

解决方案


"output": True,
"input": True,

你必须选择其中之一。Pyaudio 在同一个对象中不支持两者。


推荐阅读