Search code examples
linuxaudioalsa

Finding all the devices I can use to play PCM with ALSA


I use ALSA to play PCM samples. I open the PCM stream with this function:

int snd_pcm_open(snd_pcm_t** pcmp,
        const char* name,
        snd_pcm_stream_t stream,
        int mode);

I'm currently using "default" as the name parameter. I would like to be able to choose other devices. What I cannot understand is how I can determine what are the names of the other available devices.

I attached a USB microphone to my system and aplay and amixer seems to detect the new device. How do I determine the name of that device? Is there any ALSA function to get a list of available devices with their respective names?


Solution

  • I think you can use snd_device_name_hint for enumerating devices. Here is an example. Beware that I haven't compiled it !

    char **hints;
    /* Enumerate sound devices */
    int err = snd_device_name_hint(-1, "pcm", (void***)&hints);
    if (err != 0)
       return;//Error! Just return
    
    char** n = hints;
    while (*n != NULL) {
    
        char *name = snd_device_name_get_hint(*n, "NAME");
    
        if (name != NULL && 0 != strcmp("null", name)) {
            //Copy name to another buffer and then free it
            free(name);
        }
        n++;
    }//End of while
    
    //Free hint buffer too
    snd_device_name_free_hint((void**)hints);