Alsa混合器和GtkVolumeButton

时间:2013-01-29 10:26:59

标签: gtk alsa

我制作代码以获取和设置alsa混音器音量:

snd_mixer_elem_t *elem = NULL;
long alsa_min, alsa_max, alsa_vol;

int alsa_get_volume( void )
{
    long val;
    assert (elem);

    if (snd_mixer_selem_is_playback_mono(elem)) {
        snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_MONO, &val);
        return val;
    } else {
        int c, n = 0;
        long sum = 0;
        for (c = 0; c <= SND_MIXER_SCHN_LAST; c++) {
                if (snd_mixer_selem_has_playback_channel(elem, c)) {
                        snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_FRONT_LEFT, &val);
                        sum += val;
                        n++;
                }
        }
        if (! n) {
                return 0;
        }
        val = sum / n;
        sum = (long)((double)(alsa_vol * (alsa_max - alsa_min)) / 100. + 0.5);
        if (sum != val) {
           alsa_vol = (long)(((val * 100.) / (alsa_max - alsa_min)) + 0.5);
        }
        return alsa_vol;
    }
}

int alsa_set_volume( int percentdiff )
{
    long volume;

    alsa_get_volume();

    alsa_vol += percentdiff;
    if( alsa_vol > 100 ) alsa_vol = 100;
    if( alsa_vol < 0 ) alsa_vol = 0;

    volume = (long)((alsa_vol * (alsa_max - alsa_min) / 100.) + 0.5);

    snd_mixer_selem_set_playback_volume_all(elem, volume + alsa_min);
    snd_mixer_selem_set_playback_switch_all(elem, 1);
    muted = 0;
    mutecount = 0;

    return alsa_vol;
}

我不会通过GtkVolumeButton改变alsa混音器音量。试过这个但是当gtk按钮的值向上或向下变化时,alsa混音器总是跳到100%:

int gtk_volume_button_get_value (GtkWidget *button)
{
    return (int) (gtk_scale_button_get_value(GTK_SCALE_BUTTON(button)) * 100);
}

void gtk_volume_button_set_value (GtkWidget *button, int value)
{
    gtk_scale_button_set_value(GTK_SCALE_BUTTON(button), (gdouble) value / 100);
}

void volume_value_changed_cb(GtkVolumeButton *button, gpointer user_data)
{
    int vol = (int)(gtk_volume_button_get_value(volume_button) + 0.5);

    alsa_set_volume(vol);
}

请帮我写一个GtkVolumeButton的核心代码。

1 个答案:

答案 0 :(得分:0)

您的问题与GtkVolume无关。实际上,它来自于您使用两种不同的方法来处理音量。 alsa_get_volume为您提供绝对声级,即整数。人们会期望alsa_set_volume接受相同类型的值范围。这就是你在volume_value_changed_cb中使用它的方法:«获取音量控制的音量级别,介于0和100之间,并将其设置为当前音量。 »。

然而,实施完全不同。它的实现好像你想告诉它“加上或减去当前音量的x%”。您获得当前音量级别并添加该百分比,因此您计算的是相对声级,而不是绝对级。因此,如果您的初始声级为50%,并且您希望将其降低至45%,则可以预期您会调用alsa_set_volume (45)来执行此操作。但目前,调用alsa_set_volume (45)会将alsa_vol设置为50 + 45 = 95%。

所以你需要使用绝对量,而不是相对量。

/* newvol: Desired volume level in the [0;100] range */
int alsa_set_volume (int newvol)
{
    long volume;

    alsa_vol = CLAMP(absvol, 0, 100);

    volume = (long)((alsa_vol * (alsa_max - alsa_min) / 100.) + alsa_min);

    snd_mixer_selem_set_playback_volume_all(elem, volume);
    snd_mixer_selem_set_playback_switch_all(elem, 1);
    muted = 0;
    mutecount = 0;

    return alsa_vol;
}