How to set a Mixer's volume to a slider's volume in Unity?

那年仲夏 提交于 2020-12-31 06:48:20

问题


I'm trying to make some audio settings. Here is my script:

public AudioMixer masterMixer;
public float masterLvl;
public float musicLvl;
public float sfxLvl;

public void SetMasterVolume ()
{
    masterLvl = masterVolumeSlider.value;
    masterMixer.SetFloat("masterVol", masterLvl);
}

public void SetMusicVolume()
{
    musicLvl = musicVolumeSlider.value;
    masterMixer.SetFloat("musicVol", musicLvl);
}

public void SetSfxVolume()
{
    sfxLvl = sfxVolumeSlider.value;
    masterMixer.SetFloat("sfxVol", sfxLvl);
}

It has all the OnValueChanged(); things on the sliders. I just want to know why this doesn't work. Thanks.

EDIT: So the thing is that it changes the dB, not the volume. The new question is: How do I make it change the volume instead of dB?

EDIT 2: Screenshot.


回答1:


I think, your problem is that the mixer value (-80db - 20db) is a logarithmic scale and the slider value is linear. For example: half volume is actually about -10db, but if you connect it to a linear scale, like the slider, then half volume will end up being -40db! Which is why it sounds like it's basically silent at that point.

There's an easy way to fix it:

  1. Instead of setting the slider min / max values to -80 and 20, set them to min 0.0001 and max 1.

  2. In the script to set the value of the exposed parameter, use this to convert the linear value to an attenuation level:

     masterMixer.SetFloat("musicVol", Mathf.Log10(masterLevel) * 20);
    

It's important to set the min value to 0.0001, otherwise dropping it all the way to zero breaks the calculation and puts the volume up again.

Post:

https://forum.unity.com/threads/changing-audio-mixer-group-volume-with-ui-slider.297884/




回答2:


Here's a formula that sounds subjectively closer to how linear volume behaves usually:

    private float ValueToVolume(float value, float maxVolume)
    {
        return Mathf.Log10(Mathf.Clamp(value, 0.0001f, 1f)) * (maxVolume - zeroVolume) / 4f + maxVolume;
    }
  • It looks something like this.

  • maxVolume can be used if your AudioMixerGroup "max" volume is not 0 but -20db for example.




回答3:


You will have to deal with the dB to set the volume of a mixer. Set your slider's lower limit to -80 and upper limit to 20 and it will work fine with the mixer. If you do not want to deal with it You can either change the volume of the audio listener or the source.



来源:https://stackoverflow.com/questions/46529147/how-to-set-a-mixers-volume-to-a-sliders-volume-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!