Search code examples
javaandroidandroid-mediaplayer

Android MediaPlayer SeekTo function workaround


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.


Solution

  • 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.