1. 程式人生 > >linux利用asound控制音量

linux利用asound控制音量

#include <stdio.h>
#include <alsa/asoundlib.h>
#include <stdlib.h>
#include <string.h>
int main(int argc ,char **argv)
{
    int volume=99;
    if(argc>1)
        volume=atoi(argv[1]);
    if(volume<0)
        volume=0;
    if(volume>100)
       volume=100;
    int unmute, chn;
    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, 0, &unmute);

    snd_mixer_selem_set_playback_volume(master_element, SND_MIXER_SCHN_FRONT_LEFT, volume);
    snd_mixer_selem_set_playback_volume(master_element, SND_MIXER_SCHN_FRONT_RIGHT, volume);  /* 將 Master 切換為靜音 */
    for (chn=0;chn<=SND_MIXER_SCHN_LAST;chn++) {
      snd_mixer_selem_set_playback_switch(master_element, chn, 0);
    }  /* 將 Master 切換為非靜音 */
    for (chn=0;chn<=SND_MIXER_SCHN_LAST;chn++) {
      snd_mixer_selem_set_playback_switch(master_element, chn, 1);
    }  return 0;
}
gcc voice.c  -o setvoice -lasound