Egek92 Egek92 - 3 months ago 9
Android Question

Mediaplayer pause button followed by play, media starts from beginning

I'm trying to make a simple media player with play,pause and stop button. Play and stop buttons work fine. However pause button behaves like stop button. When I click play button after pause, it starts from beginning.

Button one = (Button) findViewById(R.id.mediaButton);
Button two = (Button) findViewById(R.id.mediaButton2);
Button three = (Button) findViewById(R.id.mediaButton3);
final MediaPlayer mp = new MediaPlayer();




one.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (mp.isPlaying()) {

return;
}

try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("Urge_Surfing.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setLooping(false);
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


});

two.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (mp.isPlaying()) {

mp.pause();
} else {
return;

}


}


});


three.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (mp.isPlaying()) {

mp.stop();
mp.reset();

} else {
return;

}


}


});

Answer

I believe the problem is the reset() call.
According to the state machine, start() is the only call required in order to resume from the same place.
Try keeping track of your state and if you are at PAUSED state, call only start() to resume.
I've used this little wrapper to keep track on current state of the MediaPlayer.