MikeC
MikeC

Reputation: 735

Setting the Initial Volume to the phones ring volume

im trying to make it so when the user opens the app it sets the volume of the music to whatever they have their phones ringer volume at. This is my code so far but im not exactly sure what the paramters on setVolume(float, float) are. The android documentation doesn't explain it well. What is my code doing wrong here?

  AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

   mPlayer = MediaPlayer.create(this, R.raw.song);
   mPlayer.setOnErrorListener(this);

   if(mPlayer!= null)
    {         
    mPlayer.setLooping(true);
    mPlayer.setVolume(currentVolume,1);
}

Upvotes: 2

Views: 2062

Answers (1)

SirPentor
SirPentor

Reputation: 2044

Looks like audio.setStreamVolume is what you want, but pass in STREAM_MUSIC instead of STREAM_RING.

Note: the music volume and ringer volume are likely to have different maximum values, so you will need to normalize them. Use getStreamMaxVolume for that.

I have not done this before, and I haven't compiled this, but the code should look something like this

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

// Get the current ringer volume as a percentage of the max ringer volume.
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
int maxRingerVolume = audio.getStreamMaxVolume(AudioManager.STREAM_RING);
double proportion = currentVolume/(double)maxRingerVolume;

// Calculate a desired music volume as that same percentage of the max music volume.
int maxMusicVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int desiredMusicVolume = (int)(proportion * maxMusicVolume);

// Set the music stream volume.
audio.setStreamVolume(AudioManager.STREAM_MUSIC, desiredMusicVolume, 0 /*flags*/);

Upvotes: 4

Related Questions