在Python中记录输出声音

2024-06-01 02:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python编程录制从笔记本电脑发出的声音。我找到了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()

问题是我得把耳机插孔和麦克风插孔连接起来。我试着换掉这几行:

input = True,
input_host_api_specific_stream_info = stream_info,

有了这些:

output = True,
output_host_api_specific_stream_info = stream_info,

但后来我发现这个错误:

Traceback (most recent call last):
File "./test.py", line 25, in
data = stream.read(chunk)
File "/Library/Python/2.5/site-packages/pyaudio.py", line 562, in read
paCanNotReadFromAnOutputOnlyStream)
IOError: [Errno Not input stream] -9975

有没有一种方法可以实例化PyAudio流,使其从计算机的输出输入,而我不必将耳机插孔连接到麦克风?有更好的办法吗?我更喜欢使用python应用程序,避免使用cocoa。


Tags: infotrueformathostmapinputdatastream
3条回答

不幸的是,没有万无一失的方法,但是Audio HijackWiretap是最好的工具。

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

您还可以查看PyJack,这是Jack的音频客户端。

我可以不使用程序化的方式给出答案。 面板>;声音>;录制>;>;启用立体声混音。 这需要司机的支持。 我还发现,这使我真正的声音回声。 至少这解决了我的问题。

相关问题 更多 >