0

我编写代码来获取和设置 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 编写一个正确的代码。

4

1 回答 1

1

您的问题与 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;
}
于 2013-01-29T15:02:19.763 回答