Search code examples
pythonaudiopyaudiorecordinginput-devices

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


I'm trying to select a device to use when I go to record using the PyAudio library in Python but I don't know how to do so. I found this code online that shows all the available input devices:

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))

This works however, how do I select a device to use from this list? I can't seem to find anywhere online about selecting a device to use so if anyone could help me out that would be great, thanks.


Solution

  • After you have listed the devices out (by printing them as you have shown in the code from the question) you can choose which index of the devices you want to use.

    i.e. it may print out

    ('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')
    

    And then to start recording from that specific device, you need to open a PyAudio stream:

    # 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()
    
    

    For more information regarding the stream options, take a look at the config specified on PyAudio's official documentation.

    If you need help with more of the script I recommend looking at the simple example for non-blocking audio with PyAudio, available on their documentation.