我正在开发使用 ALSA 声音库的 C 程序,并且我正在尝试将音量设置为特定的百分比值。我尝试遵循基于 pyalsaaudio 库和 this SO 答案 的实现。当我将元素名称设置为
"Master"
时,我的问题开始了。运行程序时遇到以下错误(见下文):snd_mixer_selem_get_playback_volume_range: Assertion 'elem' failed
。但是,如果我将元素名称设置为 "PCM"
,则音量范围检索工作正常,但我无法正确设置百分比,因为这些值采用对数刻度,无法计算出转换函数(不是 dB 函数) .
我正在开发带有 Raspberry Pi OS 64 位的 Raspberry Pi 4。也在 Ubuntu 23.04 64 位中尝试过,结果相同。
此外,当我在终端中运行
amixer scontrols
时,输出为:
Simple mixer control 'Master',0
Simple mixer control 'Capture',0
这是我正在使用的代码:
#include <stdio.h>
#include <alsa/asoundlib.h>
int main(int argc, char *argv[])
{
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);
long range = max - min;
// setting the volume to 58%
long volume = min + (range * 58/100);
snd_mixer_selem_set_playback_volume_all(elem, volume);
printf("volume min: %ld - max: %ld\n", min, max);
}
我使用以下命令来编译它
gcc -o audio audio.c -lasound
我终于找到了我的问题。我正在使用 sudo 执行脚本:
sudo ./audio
但是 ALSA 的行为与不使用 sudo 运行它的行为不同,因此解决方案是像这样运行它:
./audio
我使用 sudo 运行的原因是因为我还在同一程序中访问 GPIO,这需要 root 权限。 如果它对某人有帮助,访问 GPIO 但无需 sudo 运行程序的完整解决方案是更改其所有权和权限。
sudo chown root:root audio
sudo chmod 4755 audio
./audio