如何选择要录制的设备(Python PyAudio)



当我使用Python中的PyAudio库进行录制时,我正试图选择一个要使用的设备,但我不知道如何做到。我在网上找到了这段代码,它显示了所有可用的输入设备:

import pyaudio
p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
print("Input Device id ", i, " - ", p.get_device_info_by_host_api_device_index(0, i))

然而,这是有效的,我如何从列表中选择要使用的设备?我似乎在网上找不到任何关于选择要使用的设备的信息,所以如果有人能帮我,那就太好了,谢谢。

列出设备后(按照问题代码中显示的方式打印(,您可以选择要使用的设备索引。

即可以打印出

('Input Device id ', 2, ' - ', u'USB Sound Device: Audio (hw:1,0)')
('Input Device id ', 3, ' - ', u'sysdefault')
('Input Device id ', 11, ' - ', u'spdif')
('Input Device id ', 12, ' - ', u'default')

然后,要从特定设备开始录制,您需要打开PyAudio流:

# Open stream with the index of the chosen device you selected from your initial code
stream = p.open(format=p.get_format_from_width(width=2),
channels=1,
output=True,
rate=OUTPUT_SAMPLE_RATE,
input_device_index=INDEX_OF_CHOSEN_INPUT_DEVICE, # This is where you specify which input device to use
stream_callback=callback)
# Start processing and do whatever else...
stream.start_stream()

有关流选项的更多信息,请查看PyAudio官方文档中指定的配置。

如果你需要更多的脚本帮助,我建议你看看PyAudio的非阻塞音频的简单例子,可以在他们的文档中找到。

最新更新