使用 PyAudio 录制扬声器输出 [英] Record speakers output with PyAudio
问题描述
我正在尝试使用 PyAudio 录制计算机扬声器的输出.
我试图修改 PyAudio 文档中给出的代码示例,但它不起作用.
I'm trying to record the output from my computer speakers with PyAudio.
I tried to modify the code example given in the PyAudio documentation, but it doesn't work.
从技术上讲,没有错误.我得到文件 output.wav
并且我可以打开它,但是没有声音.在 Audacity 上,我只能看到一条直线.
Technically, there's no error. I obtain the file output.wav
and I can open it, but there's no sound. On Audacity, I can only see a straight line.
怎么了?
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
SPEAKERS = p.get_default_output_device_info()["hostApi"] #The part I have modified
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_host_api_specific_stream_info=SPEAKERS) #The part I have modified
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
推荐答案
如果有人仍然像我一样在这个问题上磕磕绊绊,我找到了一个 PyAudio fork 在 Windows 上记录输出.
In case someone is still stumbling over this like me, I found a PyAudio fork to record the output on windows.
说明:
官方 PyAudio 版本无法记录输出.但是在 Windows Vista 及更高版本中,引入了一个新的 API WASAPI,其中包括在环回模式下打开到输出设备的流的能力.在这种模式下,流将表现得像一个输入流,能够记录传出的音频流.
The official PyAudio build isn't able to record the output. BUT with Windows Vista and above, a new API, WASAPI was introduced, which includes the ability to open a stream to an output device in loopback mode. In this mode the stream will behave like an input stream, with the ability to record the outgoing audio stream.
要设置模式,必须设置一个特殊标志(AUDCLNT_STREAMFLAGS_LOOPBACK).由于官方版本不支持此标志,因此需要编辑 PortAudio 和 PyAudio,以添加回送支持.
To set the mode, one has to set a special flag (AUDCLNT_STREAMFLAGS_LOOPBACK). Since this flag is not supported in the official build one needs to edit PortAudio as well as PyAudio, to add loopback support.
新选项:
"as_loopback":(true|false)
"as_loopback":(true|false)
这篇关于使用 PyAudio 录制扬声器输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!