pythonaudiofilterpyaudiomicrophone

List all actual microphones python


How can I list every actual microphones currently available in python?

Currently i am doing this:

import pyaudio

p = pyaudio.PyAudio()

print("Available audio input devices:")
for i in range(p.get_device_count()):
    dev_info = p.get_device_info_by_index(i)
    print(f"{i}: {dev_info['name']}")

device_index = int(input("Enter the index of the audio input device you want to use: "))

I know this also prints output devices, but the results are bloated with duplicates and things that aren't actually devices.

For reference I have 3 input devices, and 2 output devices, but the script prints 29 items.

What is the proper way of 'filtering' this to only display actual devices, aka the ones available in my Settings > System > Sound ?


Solution

  • Due to PortAudio supporting multiple APIs, you see repeated mentions of the same device but on different host APIs (for reference: https://files.portaudio.com/docs/v19-doxydocs/api_overview.html). You can simply filter it out like this:

    import pyaudio
    pa = pyaudio.PyAudio()
    print("Number of devices (all APIs, input + output):"+ pa.get_device_count())
    
    for i in range (pa.get_device_count()):
       device_info = pa.get_device_info_by_index(i)
       if device_info['maxInputChannels'] != 0 and device_info['hostApi'] == 0:
           print('Device ' + str(i) + ': ' + device_info['name'])
    

    I'm sure there's an even shorter way to do it, but essentially, it comes down to which native audio APi your application wants/needs and you count the number of input devices with the same API.