How to select a specific input device with PyAudio

Cerin picture Cerin · Apr 27, 2016 · Viewed 38.9k times · Source

When recording audio via PyAudio, how do you specify the exact input device to use?

My computer has two microphones, one built-in and one via USB, and I want to record using the USB mic. The Stream class has an input_device_index for selecting the device, but it's unclear how this index correlates to the devices. For example, how do I know which device index 0 refers to? If I had to guess, I'd say 0 refers to the built-in device while 1 refers to the USB device, but I'd like to find some programmatic way of confirming this. On Linux, is there a way to get a list of these indexes and the devices they refer to?

Answer

slegroux picture slegroux · Sep 24, 2016

you can use: get_device_info_by_host_api_device_index. For instance:

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).get('name')