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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With