Search code examples
python-2.7audiodevice

Getting list of audio input devices in Python


How do I get the list of audio input devices in Linux using Python in this format as hw:0,1?

I've tried the following using pyaudio:

def getaudiodevices():
        p = pyaudio.PyAudio()
        print p.get_default_input_device_info()
        for i in range(p.get_device_count()):
                print ''#p.get_device_info_by_index(i)

I'm also able to retrieve using "arecord -l" but I need to just get it like:

hw:0,1
hw:0,2

What can I try next?


Solution

  • If the name stored by the PaDeviceInfo structure is sufficient, then you could just access the 'name' from the dict returned by get_device_info_by_index(), and then perhaps slice the information off the end:

    import pyaudio
    
    def getaudiodevices():
        p = pyaudio.PyAudio()
        for i in range(p.get_device_count()):
            print p.get_device_info_by_index(i).get('name')
    

    gives me

    HDA Intel HDMI: 0 (hw:0,3)
    HDA Intel HDMI: 1 (hw:0,7)
    HDA Intel HDMI: 2 (hw:0,8)
    HDA Intel PCH: CS4208 Analog (hw:1,0)
    HDA Intel PCH: CS4208 Digital (hw:1,1)
    hdmi
    default
    

    But this doesn't give you what you want with the default devices, the name seems to be stored as "default". In that case, executing "arecord -l" in Python can work, if that's what you're looking for. Of course, you can do the same thing for "aplay -l".

    import os
    
    def getaudiodevices():
        devices = os.popen("arecord -l")
        device_string = devices.read()
        device_string = device_string.split("\n")
        for line in device_string:
                if(line.find("card") != -1):
                    print "hw:" + line[line.find("card")+5] + "," +\
     line[line.find("device")+7]
    

    outputs

    hw:1,0