CodeMonkey
CodeMonkey

Reputation: 12424

How to convert Android stream volume to a value between 0 and 1

I am using a MediaPlayer to play sound and I want to take the current stream's volume and set it as the volume for the media player with it setVolume method.

The issue is that if I take the value of the volume like this:

audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

The value I receive is an index of the volume, while the setSound method expects a value between 0 and 1.

How do I convert the index to a value between 0 and 1?

Upvotes: 0

Views: 1108

Answers (2)

Varun K
Varun K

Reputation: 11

You can set the value between 0-1 by using the code below...

private final static int MAX_VOLUME = 100;
final float volume = (float) (1 - (Math.log(MAX_VOLUME + 1 - soundVolume) / 
Math.log(MAX_VOLUME + 1)));
mediaPlayer.setVolume(volume, volume);

Upvotes: 1

A. AMAIDI
A. AMAIDI

Reputation: 6849

Simply divide the current volume index by the max volume index of the stream

int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

float desiredValue = currentVolume / (float) maxVolume;

you can then use that value as you wish (it is beetween 0 and 1)

Upvotes: 1

Related Questions