user5804127 user5804127 - 7 months ago 17
Linux Question

Selecting audio device for playback via Python

How to get a list of audio devices in linux (like

aplay -L
) and select audio device for the output? are there any libs to import? Are they already imported?


I searched high and low for what you are asking for when writing a sound equaliser and never found a satisfactory answer.
There is an alsaaudio library available:

import alsaaudio   #alternative method pure python
for device_number, card_name in enumerate(
    print device_number, card_name

I ended up banging pacmd and cat options onto the command line, retrieving and parsing the results to discover what was what.

    sink_list = os.popen('cat /proc/asound/cards | grep "\[" | cut -c2').readlines()
    for s in sink_list:
        s = s.strip()

for pulseaudio you need pacmd

# Identify the default sound card device
    sink = os.popen('pacmd list | grep "device.master_device" | cut --delimiter== -f2').readline()
    if sink =="":
        sink = os.popen('pacmd list-cards | grep -C1 sinks | grep pci | cut --delimiter=/ -f1').readline()

It's all most unsatisfactory and un-python like but needs must when the devil drives