简体   繁体   中英

Android mediaplayer won't start after pause

I'm trying make a simple mediaplayer but the pause button doesn't work. When I click on the pause button it stops but when I click on play again it starts at the start again.

I don't know how to make one button where I can play/pause the button.

Code I currently have:

http://pastebin.com/wiDkzw5S

Thanks already!

You would need to save current position of media player and restart it later from that position using seekTo .

Something like:

int currentPos = 0;
pause.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

        if (mediaPlayer.isPlaying()) {
            currentPos = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            //change image to play
        } else {
            mediaPlayer.seekTo(currentPos);
            mediaPlayer.start();
            //again revert image to pause
        }  
    }
});

Hope it helps.

This is running test and running code, you may use this for pause and resume the media player.

int length=0;  
Button pause = (Button) findViewById(R.id.pause);
 pause.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
 if (mediaPlayer.isPlaying()) {
         mediaPlayer.pause();
        length=mediaPlayer.getCurrentPosition();    
    } else {
        mediaPlayer.seekTo(length);
        mediaPlayer.start();
          }
       }
  });

I had a similar problem, but I couldn't get it to resume using the methods above.

I discovered my pauseAllSounds() function was pausing all MediaPlayer instances in my sound pool even if they weren't already playing. When that happened, it caused an error in each instance which wasn't playing which prevented that instance from playing again later. I discovered this after some time only by happening across the console output for my running process searching for the cause. It showed line after line of errors, revealing I was trying to pause from an invalid state.

// Make sure you test isPlaying() before pausing
public void pause() {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
        position = mediaPlayer.getCurrentPosition();
    }
}

Once I added the test to only pause if it was already playing, everything worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM