Linux Set ALSA master volume from C code
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6787318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set ALSA master volume from C code
提问by trenki
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'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.
I'm totally unfamiliar with ALSA, so making my own minimal example will take time. I would be happy if anyone could provide one.
采纳答案by trenki
The following works for me. The parameter volume is to be given in the range [0, 100]. Beware, there is no error handling!
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);
}