如何 select 使用哪个设备录制 (Python PyAudio)

How to select which device to record with (Python PyAudio)

我正在尝试 select 一个设备,以便在我使用 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))

但是这可行,我如何select 使用此列表中的设备?我似乎无法在网上找到任何关于 select 使用设备的信息,所以如果有人能帮助我,那就太好了,谢谢。

列出设备后(通过打印它们,如问题代码中所示),您可以选择要使用的设备索引。

即它可能会打印出

('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's official documentation 上指定的配置。

如果您需要有关脚本的更多帮助,我建议您查看使用 PyAudio 的非阻塞音频的简单示例,available on their documentation.