问题
I have two buttons that will start and stop a song, when i start the app I can play the song and then stop it again. However when i wanna start it again it doesn't work.
final Button stop = (Button) findViewById(R.id.stop);
stop.setVisibility(View.GONE);
final Button play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
play.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
stop.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
}
});
回答1:
in play.onclicklistner
mp = MediaPlayer.create(Peshmerga.this, R.raw.sppeshmerga);
mp.start();
add following to your stop.onclicklistner
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
you need to create everytime you click play button .
回答2:
I guess you want to start again by play button. Add the following code above the mp.start()
method:
mp.reset();
mp.prepare();
mp.start();
I guess you have rest of things set properly and in stop button use the following:
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
回答3:
Look at the state diagram image in the following link:
-----------------------------------------android-mediaplayer-sample-code----------------------------------------------

mp.reset();
mp.prepare();
mp.start();
回答4:
The Play Button Click Listener:
playButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
try{
if(!mMediaPlayer.isPlaying()){
mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);
mMediaPlayer.start();
}
}
catch (Exception e){
}
}
});
Stop Button Click Listener:
stopButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);
}
}
});
来源:https://stackoverflow.com/questions/25404731/play-button-doesnt-work-after-music-is-stopped-with-stop-button