How do I get the inverse of the logarithmic value for an audio slider?

I’m setting up a volume slider for my game. All the tutorials are saying to change the slider value using mathf.log10(volume) * 20 so I can get a linear value that sounds right according to people’s expectation of sound.
I did that much, and it works just fine.

But now I need to set the slider value so that it has the correct value when the user opens the menu, which means I need to retrieve the value set in the audio mixer, and then un-logarithmic it to turn it back into a 0 to 1 value.

What would that equation look like?

(Or is there a better way to go about this?)

1 Like

The logarithm is the inverse function of the power function. So the log to the base 10 of a values gives you the exponent.

exp = log10(val)

The inverse is

val = pow(10, exp)

Of course when you multiply by 20, you have to divide by 20 first

val = math.pow(10, exp / 20f);
exp = math.log10(val)*20;

Those should be exactly the opposite of each other.

2 Likes

My additional tip for this would be to spread awareness of services like wolframalpha
where you can just type x = log(v) * 20, solve for v
and get v = e^{x/20} as a solution
or v = 10^{x/20} after specifying that log stands for the base 10 logarithm (as opposed to the natural logarithm).

This translates to val = MathF.Pow(10f, exp / 20f) in code.
There are other similar services as well, which work perfectly for simple formula inversions if you know how to ask.

1 Like