Saturday, October 20, 2012

Android MusicPlayer getVolume()


Bonjour,

The android.media.MediaPlayer is useful to play a song and control its volume independently of the AudioManager.STREAM_MUSIC volume. However there is no way to get the current volume of the MediaPlayer.

Hence the class below... It provides us with access to the current volume of the player.

import android.media.MediaPlayer;

public class ImprovedMediaPlayer extends MediaPlayer
{
 private float currentVol = 1.0f;
 
 public float getVolume()
 {
  return currentVol;
 }
 
 public boolean setVolume(float newVol)
 {
  if (newVol <= 0)
   newVol = 0f;
  else if (newVol >= 1.0f)
   newVol = 1.0f;
  
  boolean volChanged = (Math.abs(newVol - currentVol) > 0.0001f);
  this.setVolume(newVol, newVol);
  return volChanged;
 }

 
 @Override
 public void setVolume(float leftVolume, float rightVolume)
 {
  currentVol = leftVolume;
  super.setVolume(leftVolume, rightVolume);
 }
}

Enjoy,
Sean

No comments:

Post a Comment