Hi - I’m doing an audio experiment where recording the sound coming out of my speakers gives me a number between around 0 and 20. I want to convert this number to something between 0 and 1, so that I can translate the volume level gets translated to the scale of an object. How do I do this? My basic setup is:
var audioVal:float = audio.GetOutPutData(...); //gives the audio in decibels
var scaleVal:float; //this value will give a scale between 0 and 1;
scaleVal = Mathf.Clamp(audioVal,0,1); //this doesn't seem to work. The value always ends up being at the maximum or minimum end of the scale.
Mathf.Clamp() does not scale a value; it restricts the value to the range. For example, if you clamp between (0, 1), any value greater than 1 will yield a clamped value of 1, and any value less than zero will yield zero; for a value inside the clamp range, the value will be unchanged.
To scale, you need to divide your raw value by the total range, and account for an offset if min != 0. For a range of (min, max):
scaledValue = (rawValue - min) / (max - min);
For the common case where min == 0:
scaledValue = rawValue / max;
Just divide by 20, or you can use Mathf.InverseLerp for arbitrary ranges. Clamp won’t work because it just clamps numbers, it doesn’t try to scale anything.
If the range you’re getting is exactly between 0 and 20, then replace your third line with:
scaleVal = audioVal / 20.0;
The code you’re using isn’t working because Mathf.Clamp merely restricts values to the range given, rather than doing a transformation from one space to another.
Just in case you want to stop at some point, this code works just perfectly for that!!!
var scaledValue = Mathf.Clamp(value / maxValue, minValue, maxValue);
Enjoy