Search code examples
linuxalsalibalsalibasound

How to get PCM device path in ALSA?


What is the easiest way in ALSA library to get the file name of the physical playback device from a pcm handle or name?

For example for the pcm device hw:0,0 I would like to get the /dev/snd/pcmC0D0p. This is rather simple (just transfer the indexes), but for "default" or any other alias it is not so obvious.


Solution

  • To answer myself. There is an indirect way to do this by obtaining the card and device number from the snd_pcm_info.

        int err;
        const char *device_name = "default";
        snd_pcm_t *pcm;
    
        err = snd_pcm_open(&pcm, device_name, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
        if (err < 0) {
            fprintf(stderr, "Failed to open audio device '%s': %s\n", device_name, snd_strerror(err));
            return false;
        }
    
        snd_pcm_info_t *info;
        err = snd_pcm_info_malloc(&info);
        if (err < 0) {
            fprintf(stderr, "Failed to allocate PCM info: %s\n", snd_strerror(err));
            goto fail;
        }
        err = snd_pcm_info(pcm, info);
        if (err < 0) {
            fprintf(stderr, "Failed to get PCM device info: %s\n", snd_strerror(err));
            snd_pcm_info_free(info);
            goto fail;
        }
    
        int card_no = snd_pcm_info_get_card(info);
        if (card_no < 0) {
            fprintf(stderr, "Failed to get PCM card number: %s\n", snd_strerror(card_no));
            snd_pcm_info_free(info);
            goto fail;
        }
    
        unsigned dev_no = snd_pcm_info_get_device(info);
    
        printf("The ALSA path is: /dev/snd/pcmC%dD%up\n", card_no, dev_no);
        snd_pcm_info_free(info);
    fail:
        snd_pcm_close(pcm);