Use ALSA API to get all input audio devices

60 views Asked by At

I want to write a code that uses ALSA API to iterate over all the audio devices and prints the devices which are defined as input (microphones).

This is my code:

#define MAX_DEV_STR_LEN 6
#include <alsa/asoundlib.h>
int main(void)
{
    snd_ctl_t *ctlp;
    snd_ctl_card_info_t *info;
    int *rcard;
    int index, err;
    rcard = &index;
    index = -1;
    char *name = malloc(MAX_DEV_STR_LEN);
    while(1)
    {
        snd_card_next(rcard);
        if(index == -1)
            break;
        sprintf(name, "hw:%d", *rcard);
        if((err = snd_ctl_open(&ctlp, name, SND_CTL_NONBLOCK)) != 0)
        {
            printf("Error opening the card: %d\n", err);
            return err;
        }
        printf("Card number %d has opened succesfully\n", *rcard);
        snd_ctl_card_info_malloc(&info);
        if((err = snd_ctl_card_info(ctlp, info)) != 0)
        {
            printf("Error obtaining the info\n");
            return err;
        }


        // get info here...


        snd_ctl_card_info_clear(info);
    }
    return 0;
}

I can't seem to find a way to get the info I need.I searched here. But couldn't find a solution.

If anyone can guide me I will appreciate it. Thank you!

1

There are 1 answers

1
Antoni On

Have you looked at the similar questions already? Here's one, it mentions that snd_device_name_hint() may help a lot with getting the list of plughw or hw devices. My suggestion is to take a look at the source code of the aplay / arecord command, especially the pcm_list() function - this seems to be the function preparing the list you want.

To check if your list is correct use arecord -L.