在python中记录输出声音

aar*_*acy 8 python audio macos audio-streaming

我想以编程方式记录我的笔记本电脑中出现的声音.我发现PyAudio并想出了以下完成任务的程序:

import pyaudio, wave, sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = sys.argv[1]

p = pyaudio.PyAudio()
channel_map = (0, 1)

stream_info = pyaudio.PaMacCoreStreamInfo(
    flags = pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice,
    channel_map = channel_map)

stream = p.open(format = FORMAT,
                rate = RATE,
                input = True,
                input_host_api_specific_stream_info = stream_info,
                channels = CHANNELS)

all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
        data = stream.read(chunk)
        all.append(data)
stream.close()
p.terminate()

data = ''.join(all)
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
Run Code Online (Sandbox Code Playgroud)

问题是我必须将耳机插孔连接到麦克风插孔.我试着更换这些线:

input = True,
input_host_api_specific_stream_info = stream_info,
Run Code Online (Sandbox Code Playgroud)

用这些:

output = True,
output_host_api_specific_stream_info = stream_info,
Run Code Online (Sandbox Code Playgroud)

但后来我得到这个错误:

回溯(最近一次调用最后一次):
文件"./test.py",第25行,在
data = stream.read(chunk)
文件"/Library/Python/2.5/site-packages/pyaudio.py",第562行,在读取
paCanNotReadFromAnOutputOnlyStream)
IOError:[Errno Not input stream] -9975

有没有办法实例化PyAudio流,以便从计算机的输出输入,我不必将耳机插孔连接到麦克风?有没有更好的方法来解决这个问题?我宁愿坚持使用python应用程序并避免使用可可.

Joã*_*eno 5

您可以安装Soundflower,它允许您创建额外的音频设备并在它们之间路由音频.这样,您可以将系统的输出定义到Soundflower设备,并使用PyAudio从中读取音频.

你也可以看看杰克的音频客户端PyJack.