Finding all mixer groups

Updated: April 19, 2023

You can get a complete list of mixer groups by calling snd_mixer_groups().

You usually call snd_mixer_groups() twice: once to get the total number of mixer groups, then a second time to actually read their IDs. The arguments to the call are the mixer handle and a snd_mixer_group_t structure. The structure contains a pointer to where the groups' identifiers are to be stored (an array of snd_mixer_gid_t structures), and the size of that array. The call fills in the structure with how many identifiers were stored, and indicates if some couldn't be stored because they would exceed the storage size.

Here's a short example (snd_strerror() prints error messages for the sound functions):

while (1)
{
    memset (&groups, 0, sizeof (groups));
    if ((ret = snd_mixer_groups (mixer_handle, &groups) < 0))
    {
       fprintf (stderr, "snd_mixer_groups API call - %s",
                snd_strerror (ret));
    }

    mixer_n_groups = groups.groups_over;
    if (mixer_n_groups > 0)
    {
        groups.groups_size = mixer_n_groups;
        groups.pgroups = (snd_mixer_gid_t *) malloc (
           sizeof (snd_mixer_gid_t) * mixer_n_groups);

        if (groups.pgroups == NULL)
            fprintf (stderr, "Unable to malloc group array - %s",
                     strerror (errno));

        groups.groups_over = 0;
        groups.groups = 0;

        if (snd_mixer_groups (mixer_handle, &groups) < 0)
            fprintf (stderr, "No Mixer Groups ");

        if (groups.groups_over > 0)
        {
            free (groups.pgroups);
            continue;
        }
        else
        {
            printf ("sorting GID table \n");
            snd_mixer_sort_gid_table (groups.pgroups, mixer_n_groups,
                snd_mixer_default_weights);
            break;
        }
    }
}