开发者

int to float for mediaplayer.setVolume()

I am using a seekbar to change the volume of my MediaPlayer. The progress level is what I am using which gives a "1 to 100" int. I ne开发者_开发问答ed to convert that into the float range of 0.0f to 1.0f. What is the correct way of doing that?

Thanks guys


float fVal = (float)val / 100; should do the trick.


divide by 100

int intValue = 1;
float floatValue = intValue/100.0;


Very late in the day, but as I was just reading up on this very subject I thought it worth posting an answer that doesn't just perform a straight linear scaling of the slider value 0 - 100 into a float value 0.0 - 1.0 and explain why you should be doing it differently.

So the API documentation for MediaPlayer.setVolume(float, float) states, in passing, that "UI controls should be scaled logarithmically" but doesn't explain why.

Sound as we hear it is measured in decibels (db), on a logarithmic scale. In simplified terms (over-simplified if you are an audio buff), twice the decibels = twice the volume. But because the decibel scale is logarithmic, the distance on the scale from (for example) 0 - 3db is bigger than the distance on the scale from 3db to 6db.

The most obvious effect of using linear scaling instead of logarithmic is that the volume with the slider at maximum is much more than twice as loud as the volume at half way, so most of the noticeable change in volume level happens in the lower three quarters (approximately) of the slider range rather than in an (apparently) linear fashion across the full slider range. And this is why straight linear scaling isn't quite the right way to translate a slider position into a value for the setVolume method.

Here's a simple function that will take your slider value (assumed to lie in the range 0 - 100), convert it into a logarithmic value and scale it:

private float scaleVolume(int sliderValue) {

    double dSliderValue = sliderValue;
    double logSliderValue = Math.log10(dSliderValue / 10);
    double logMaxSliderValue = Math.log10(10);
    float scaledVolume = (float) (logSliderValue / logMaxSliderValue);

    return scaledVolume;

}

Now, the slider at 50 (the center position) will produce a sound that is about half as loud as when the slider is at 100 (the top position), and the slider at 25 will produce a sound that is half as loud as when the slider is at 50.

Be aware that your perception of what is "twice as loud" will be affected by the kind of audio you are playing as well as the quality of the speaker and how hard it is being pushed...


To map linearly to the range 0.0 to 1.0 use

int n = <some value>;
float val = (float)(n - 1)/99;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜