I am creating a very simple media player app. I would like to resume the song from the SeekTo position that I have captured using getCurrentPosition. However seekTo does not start from the position I have captured but from the beginning.
Code to capture current position, pause and change button text to Click to resume
int media_length = mediaplayer.getCurrentPosition();
Toast.makeText(this,"media length is"+media_length, Toast.LENGTH_LONG).show();
mbutton.setText("Click to Resume");
mediaplayer.pause();
Code to seekTo captured position, start and change button text to Click to Pause
mediaplayer.seekTo(media_length);
mediaplayer.start();
mbutton.setText("Click to Pause");
A couple of posts are there already related to it but they seem to claim a bug in Android. Ref: MediaPlayer seekTo doesn't work and is there any workaround for this? appreciate any help.
Using MediaPlayer. One of the most important components of the media framework is the MediaPlayer class.
The Media Player requires a SurfaceHolder object for displaying video content, assigned using the setDisplay() method. The Surface View is a wrapper around the Surface Holder object. Note that we must implement the SurfaceHoler. Callback interface.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
You can try below code. It is working for me...
public void forwardSong() {
if (mPlayer != null) {
int currentPosition = mPlayer.getCurrentPosition();
if (currentPosition + seekForwardTime <= mPlayer.getDuration()) {
mPlayer.seekTo(currentPosition + seekForwardTime);
} else {
mPlayer.seekTo(mPlayer.getDuration());
}
}
}
You can pause mediaplayer before this and just call start method after this method.
Try to use the callback MediaPlayer.OnSeekCompleteListener.
Important : In this sample, i've added SystemClock.sleep(200)
because onSeekComplete(MediaPlayer arg0)
is called too soon by the player BEFORE seekTo is really completed.
mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer arg0) {
Log.d(TAG, "onSeekComplete() current pos : " + arg0.getCurrentPosition());
SystemClock.sleep(200);
mMediaPlayer.start();
}
});
try {
mMediaPlayer.seekTo(mCurrentPos);
} catch (IllegalStateException e){
Log.d(TAG, e.getLocalizedMessage(), e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With