Search code examples
javaandroid-studio-3.0android-music-player

In my Androidstudio music player pause button problem


When I press the pause button and then press the play button song plays from the pause position. But when the song ends and then press the play button song plays from the pause position, not from the starting.

Pasting my code here

 public void play(View view){
    if(mediaPlayer==null) {

        mediaPlayer = MediaPlayer.create(this, R.raw.ennasona);
        mediaPlayer.start();
    }

    else if (!mediaPlayer.isPlaying()){

        int nowMusicPosition = 0;

        if (nowMusicPosition == mediaPlayer.getDuration()){

            mediaPlayer = MediaPlayer.create(this, R.raw.ennasona);
            mediaPlayer.start();
        }
        else {
            mediaPlayer.seekTo(pauseCurrentPosition);
            mediaPlayer.start();
            nowMusicPosition = mediaPlayer.getCurrentPosition();

        }
    }
}
public void pause(View view){

    if(mediaPlayer!=null) {

        mediaPlayer.pause();

        pauseCurrentPosition = mediaPlayer.getCurrentPosition();

    }
}
public   void stop(View view){

    if (mediaPlayer!=null)

    mediaPlayer.stop();

    mediaPlayer = null;
}

Solution

  • Looking at the API I would say you're doing it too complicated. You don't have to remember the position, because if you're pausing the playback, the MediaPlayer should remember the position itself.

    So just use play(), pause() and you're safe. Don't seek().

    The problems with your code are here:

    else if (!mediaPlayer.isPlaying()){
        // this is called nowMusicPosition, down there you've used pauseCurrentPosition
        // this always gets 0, never changes
        int nowMusicPosition = 0;
        if (nowMusicPosition == mediaPlayer.getCurrentPosition()){
             // now you're recreating the MediaPlayer. why?
            mediaPlayer = MediaPlayer.create(this, R.raw.ennasona);
            mediaPlayer.start();
        } else {
            // if video at its end gets stopped, the
            // getCurrentPosition() delivers the last
            // position in the video and you get down
            // here and you're seeking to the paused
            // position again
            mediaPlayer.seekTo(pauseCurrentPosition);
            mediaPlayer.start();
            // now you're setting nowMusicPosition, but it gets 0 again if pressing play again, see above
            nowMusicPosition = mediaPlayer.getCurrentPosition();
        }
    }