MediaPlayer pause doesnt work in android

2019-02-21 06:02发布

问题:

I use the following code to pause the play of an audio file. but it doesn't pause. What is wrong with the code. Any suggesstion...

boolean play=false;
int flag=0;
mPlay.setOnClickListener(new OnClickListener() {

public void onClick(View v) { mPlayer = new MediaPlayer(); if(play==false) { flag++; if(flag==1) { playAudio(); } else { mPlayer.start(); } mPlay.setText("Pause"); play=true; } else if(play==true) { mPlayer.pause(); mPlay.setText("Play"); play=false; } mPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub play=false; flag=0; } });

回答1:

Problem lays here: mPlayer = new MediaPlayer(); You're initializing your player on every click, so what you're trying to pause is a completely new player that cannot be paused, cause it doesn't play. You must initialize the player outside of onClick method.