在python中记录输出声音 [英] record output sound in python
问题描述
我想用 python 以编程方式记录我的笔记本电脑发出的声音.我找到了 PyAudio
并想出了以下完成任务的程序:
i want to programatically record sound coming out of my laptop in python. i found PyAudio
and came up with the following program that accomplishes the task:
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()
问题是我必须将耳机插孔连接到麦克风插孔.我尝试替换这些行:
the problem is i have to connect the headphone jack to the microphone jack. i tried replacing these lines:
input = True,
input_host_api_specific_stream_info = stream_info,
这些:
output = True,
output_host_api_specific_stream_info = stream_info,
但后来我收到此错误:
回溯(最近一次调用最后一次):
文件./test.py",第 25 行,在
数据 = 流.读取(块)
文件/Library/Python/2.5/site-packages/pyaudio.py",第 562 行,读取
paCanNotReadFromAnOutputOnlyStream)
IOError: [Errno Not input stream] -9975
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 应用程序并避免使用可可.
is there a way to instantiate the PyAudio stream so that it inputs from the computer's output and i don't have to connect the headphone jack to the microphone? is there a better way to go about this? i'd prefer to stick w/ a python app and avoid cocoa.
推荐答案
您可以安装Soundflower,它允许您创建额外的音频设备并在它们之间路由音频.通过这种方式,您可以定义系统对 Soundflower 设备的输出,并使用 PyAudio 从中读取音频.
You can install Soundflower, which allows you to create extra audio devices and route audio between them. This way you can define your system's output to the Soundflower device and read the audio from it using PyAudio.
这篇关于在python中记录输出声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!