29

I've been looking for a simple C code example to set the master volume of the ALSA mixer but could not find anything simple for this supposedly common operation.

I'm totally unfamiliar with ALSA, so making my own minimal example will take time. I would be happy if anyone could provide one.

Jonathan Henson
  • 7,648
  • 3
  • 25
  • 49
trenki
  • 6,741
  • 7
  • 42
  • 61

1 Answers1

51

The following works for me. The parameter volume is to be given in the range [0, 100]. Beware, there is no error handling!

void SetAlsaMasterVolume(long volume)
{
    long min, max;
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";
    const char *selem_name = "Master";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
    snd_mixer_selem_set_playback_volume_all(elem, volume * max / 100);

    snd_mixer_close(handle);
}
trenki
  • 6,741
  • 7
  • 42
  • 61
  • 3
    What header file are these under? – Jonathan Henson Sep 30 '11 at 21:13
  • 5
    @JonathanHenson: #include . I think there might be one that includes less, maybe #include . – trenki Oct 01 '11 at 09:42
  • 2
    I guess I could have just retrieved the output from pkg-config --cflags alsa. Anyhow thanks! – Jonathan Henson Oct 04 '11 at 15:58
  • that's great! Thank you, @trenki :) – madper Apr 25 '12 at 07:08
  • @dreamlax: that's part of the mixer elements, too. I think it's the mute melem – dom0 Aug 03 '13 at 10:19
  • @trenki, Thanks for example, I have different situation, plz help...I am opening two pcm_snd_pcm_open() handles, i want to control volume of two instances. How can i set volume independently ? I means using which API? ...Any other idea? – JRC Oct 06 '14 at 10:15
  • 2
    @trenki, Master does not exist for me as elem. How can i get all the couple card/elem name ? "Default" card name seems to be ok for me for example even if aplay -l/-L does not show default as card name.... I tried a piece of code to enumerate all card/elem without success : https://fossies.org/linux/audacity-minsrc/lib-src/portmixer/src/px_linux_alsa.c – ArthurLambert Nov 03 '15 at 17:33
  • @ArthurLambert I found that if I run "alsamixer" it gives the elem names there... in my case it was "Playback" and "Headphone". – Michael Jan 12 '16 at 23:29
  • 2
    This seems to be the best documentation available on using the mixer API. Can it be improved by some comments explaining why the functions need to be called? The actual API documentation is extremely sparse. – Remco Poelstra Dec 14 '18 at 11:15
  • @ArthurLambert You can also list all the mixers by using "amixer contents" – C. Zach Martin Jan 07 '20 at 22:45