https://www.alsa-project.org/alsa-doc/alsa-lib/group___simple_mixer.html
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <stdarg.h> #include <ctype.h> #include <math.h> #include <errno.h> #include <assert.h> #include <alsa/asoundlib.h> #include <sys/poll.h> #include <stdint.h> #include "amixer.h" //使用 amixer scontrols,中的选项 char * sctrlstr = "Digital Input"; int main() { setCapVal(); return 0; } //一个简单使用的例子 int setCapVal() { long volMin, volMax, leftVal, rightVal; volMin = 0; //声音范围 volMax = 0; leftVal = 0; //左右声道音量 rightVal = 0; int err; static snd_mixer_t *handle = NULL; snd_mixer_elem_t *elem; snd_mixer_selem_id_t *sid; snd_mixer_selem_id_alloca(&sid); //打开混音器设备 if ((err = snd_mixer_open(&handle, 0)) < 0) { printf("snd_mixer_open Err "); return err; } snd_mixer_attach(handle, "default"); snd_mixer_selem_register(handle, NULL, NULL); snd_mixer_load(handle); //循环找到自己想要的element elem = snd_mixer_first_elem(handle); while(elem) { //比较element名字是否是我们想要设置的选项 if ( strcmp( sctrlstr, snd_mixer_selem_get_name (elem)) == 0) { printf( "elem name : %s ", snd_mixer_selem_get_name (elem) ); break; } //如果不是就继续寻找下一个 elem = snd_mixer_elem_next(elem); } if (!elem) { printf("snd_mixer_find_selem Err "); snd_mixer_close(handle); handle = NULL; return -ENOENT; } //输出elem的名字 printf( "elem name : %s ", snd_mixer_selem_get_name (elem) ); snd_mixer_selem_get_capture_volume_range(elem, &volMin, &volMax); printf("音量范围: %ld -- %ld ", volMin, volMax); snd_mixer_handle_events(handle); snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_FRONT_LEFT, &leftVal); snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_FRONT_RIGHT, &rightVal); printf("当前音量: leftVal = %ld, rightVal = %ld ", leftVal, rightVal); //判断是不是单声道 if( snd_mixer_selem_is_playback_mono( elem) ) { //单声道 snd_mixer_selem_set_playback_volume(elem,SND_MIXER_SCHN_FRONT_LEFT, 45); printf("单声道: 45 "); } else { //左音量 snd_mixer_selem_set_playback_volume(elem,SND_MIXER_SCHN_FRONT_LEFT, 45); //右音量 snd_mixer_selem_set_playback_volume(elem,SND_MIXER_SCHN_FRONT_RIGHT, 67); printf("双声道: 45, 67 "); } //关闭混音器设备 snd_mixer_close(handle); handle = NULL; }