Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding available sound cards on Linux programmatically

Tags:

c

linux

alsa

Is there a way to get a list of available sound cards on the system programmatically using asoundlib and C? I want it with the same information as /proc/asound/cards.

like image 523
thelinuxer Avatar asked Sep 02 '11 20:09

thelinuxer


1 Answers

You can iterate over the cards using snd_card_next, starting with a value of -1 to get the 0th card.

Here's sample code; compile it with gcc -o countcards countcards.c -lasound:

#include <alsa/asoundlib.h>
#include <stdio.h>

int main()
{
    int totalCards = 0;   // No cards found yet
    int cardNum = -1;     // Start with first card
    int err;

    for (;;) {
        // Get next sound card's card number.
        if ((err = snd_card_next(&cardNum)) < 0) {
            fprintf(stderr, "Can't get the next card number: %s\n",
                            snd_strerror(err));
            break;
        }

        if (cardNum < 0)
            // No more cards
            break;

        ++totalCards;   // Another card found, so bump the count
    }

    printf("ALSA found %i card(s)\n", totalCards);

    // ALSA allocates some memory to load its config file when we call
    // snd_card_next. Now that we're done getting the info, tell ALSA
    // to unload the info and release the memory.
    snd_config_update_free_global();
}

This is code reduced from cardnames.c (which also opens each card to read its name).

like image 196
thelinuxer Avatar answered Nov 01 '22 06:11

thelinuxer