An Android SeekBar for your MediaPlayer

Nico Heid's picture

android logoWe all like a playback progress bar underneath our media players, so we can see how far we are and, if necesary, drag the thumb to were we want it to be.

Lets do this on Android: enter http://developer.android.com/reference/android/widget/SeekBar.html

As we will need a Runnable to update the bar regularly, let you class implement Runnable. Let's look at the run() method.

  1.    @Override
  2.     public void run() {
  3.         // mp is your MediaPlayer
  4.         // progress is your ProgressBar
  5.  
  6.         int currentPosition = 0;
  7.         int total = mp.getDuration();
  8.         progress.setMax(total);
  9.         while (mp != null && currentPosition < total) {
  10.             try {
  11.                 Thread.sleep(1000);
  12.                 currentPosition = mp.getCurrentPosition();
  13.             } catch (InterruptedException e) {
  14.                 return;
  15.             } catch (Exception e) {
  16.                 return;
  17.             }
  18.             progress.setProgress(currentPosition);
  19.         }
  20.     }

What we're doing here is set the ProgressBar to our current position, then sleep for a second and do it again.

That was easy.

So, as we do want to use the SeekBar for jumping around in our playback, also implement SeekBar.OnSeekBarChangeListener.
The interesting part is the onProgressChanged method:

  1.   @Override
  2.     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  3.         if (fromUser) {
  4.             mp.seekTo(progress);
  5.         }
  6.     }

So we set our MediaPlayer to the place where the thumb ended up.

Now what's that fromUser doing there?

It indicates that the change was made by the user. That's important, as we're calling .setProgress every second, as you can see in the first code snippet. If we do not check if this was a user action, we're seeking in our own MediaPlayer every second, which will make your playback sound as if it is skipping around, which it actually is.

And that was all the magic there is to it.

A little thank you goes to stackoverflow, as I overlooked the fromUser part in my implementation at first.

Comments

Phillip Steffensen's picture

Great article! Thanx!

Anonymous's picture

the sleep thread has to be after the currentPosition = mp.getCurrentPosition(); because if you want to terminate the the mp object ondestroy or on backpressed you'll not get an exception.

priya's picture

Hi,

can u pl help me . If i drag the seekbar in the middle, it goes back and starts to play from starting. How to resolve this ? See my code below :

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
if (getMusicService().isPlaying()) {
getMusicService().seekTo(progress);
} else {
try {
start();
getMusicService().seekTo(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}