Linux如何获取系统音量并修改系统音量

ALSA

ALSA的体系结构

官方主页 :https://www.alsa-project.org/wiki/Main_Page

主要跟编程相关是

  • alsa-lib. ALSA 应用库(最常用)

ftp://ftp.alsa-project.org/pub/lib/alsa-lib-1.0.22.tar.bz2

https://www.alsa-project.org/files/pub/lib/alsa-lib-1.2.6.1.tar.bz2

  • alsa-driver 一些常见芯片的ALSA驱动代码,一般内核会集成.

ftp://ftp.alsa-project.org/pub/driver/alsa-driver-1.0.22.1.tar.bz2

  • alsa-firmware 一些DSP或ASIC的专用的微码(运在芯片之上,启动时由LINUX装入到硬件中).

ftp://ftp.alsa-project.org/pub/firmware/alsa-firmware-1.0.20.tar.bz2

  • alsa-utils 一般ALSA小的测试工具.如aplay/arecord 播放和录音小程序.

ftp://ftp.alsa-project.org/pub/utils/alsa-utils-1.0.22.tar.bz2

  • alsa-oss 用alsa接口模拟旧的oss接口.

ftp://ftp.alsa-project.org/pub/oss-lib/alsa-oss-1.0.17.tar.bz2

直接安装ALSA
apt-get install libasound2-dev

实例

以下代码编译的时候要添加libasound.so库

#include <stdio.h>
#include <alsa/asoundlib.h>
int snd_mixer_volume(void)
{
int unmute, chn;
snd_mixer_selem_channel_id_t chn_id;
long al, ar;
snd_mixer_t *mixer;
snd_mixer_elem_t *master_element;

snd_mixer_open(&mixer, 0);
snd_mixer_attach(mixer, "default");
snd_mixer_selem_register(mixer, NULL, NULL);
snd_mixer_load(mixer);
/* 取得第一個 element,也就是 Master */
master_element = snd_mixer_first_elem(mixer);
/* 設定音量的範圍 0 ~ 100 */
snd_mixer_selem_set_playback_volume_range(master_element, 0, 100);
/* 取得 Master 是否靜音 */
snd_mixer_selem_get_playback_switch(master_element, (snd_mixer_selem_channel_id_t)0, &unmute);
if (unmute)
{
printf("Master is Unmute.\n");
}
else
{
printf("Master is Mute.\n");
}
/* 取得左右聲道的音量 */
snd_mixer_selem_get_playback_volume(master_element, SND_MIXER_SCHN_FRONT_LEFT, &al);
snd_mixer_selem_get_playback_volume(master_element, SND_MIXER_SCHN_FRONT_RIGHT, &ar);
/* 兩聲道相加除以二求平均音量 */
printf("Master volume is %d\n", (al + ar) >> 1);
/* 設定 Master 音量 */
snd_mixer_selem_set_playback_volume(master_element, SND_MIXER_SCHN_FRONT_LEFT, 24);
snd_mixer_selem_set_playback_volume(master_element, SND_MIXER_SCHN_FRONT_RIGHT, 24);

/* 將 Master 切換為靜音 */
for (chn=0;chn<=SND_MIXER_SCHN_LAST;chn++)
{
snd_mixer_selem_set_playback_switch(master_element, (snd_mixer_selem_channel_id_t)chn, 0);
}
/* 將 Master 切換為非靜音 */
for (chn=0;chn<=SND_MIXER_SCHN_LAST;chn++)
{
snd_mixer_selem_set_playback_switch(master_element, (snd_mixer_selem_channel_id_t)chn, 1);
}

return 0;
}

OSS

介绍:https://www.iteye.com/blog/yidongkaifa-1813484

// 设置音量
int general_volume(int* data)
{
int mixer_fd;// 用于调音器标识符
//mixer_fd = oss_get_mixer();// 获得调音器的标识符
if ((mixer_fd = open("/dev/mixer", O_WRONLY, 0)) == -1) {
/* Open of device failed */
perror(DEVICE_NAME);
exit(1);
}
if (*data < 0 || *data > 100)
{
// 判断输入的数值是否有误
printf("输入的音量调节值有误\n");
return 0;
}

if (ioctl(mixer_fd, SOUND_MIXER_WRITE_VOLUME, data) == -1)
{
// 打开声卡设备文件,设置音量
printf("无法打开指定声卡\n");
return 0;
}
close(mixer_fd);

return 1;
}
(0)
上一篇 2022-05-12 14:37
下一篇 2022-05-12 14:39

相关推荐