We 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.
@Override public void run() { // mp is your MediaPlayer // progress is your ProgressBar int currentPosition = 0; int total = mp.getDuration(); progress.setMax(total); while (mp != null && currentPosition < total) { try { Thread.sleep(1000); currentPosition = mp.getCurrentPosition(); } catch (InterruptedException e) { return; } catch (Exception e) { return; } progress.setProgress(currentPosition); } }
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:
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mp.seekTo(progress); } }
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.
The post An Android SeekBar for your MediaPlayer appeared first on united-coders.com.