Reputation: 37
What i am trying to accomplish is I stopped the music, then when I press the play button again, the media player will play it. But the problem I facing now is after I pressed the stop button, I can't play the music again. Here is my code:
Button play,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_beginagain);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
final MediaPlayer sound = MediaPlayer.create(Audio_BeginAgain.this, R.raw.beginagain);
final MediaPlayer mp = new MediaPlayer();
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.stop();
}
});
}
Upvotes: 0
Views: 1189
Reputation: 11
You can simply add a completion listener and then use mediaPlayer.seekto(0)
and start()
:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
});
}
Upvotes: 1
Reputation: 910
It's exactly what Md Abdul Gafur said..
Each time you want re-play the MediaPlayer
you must initialize it new with create()
.
Look at this code:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Code copied from: Android MediaPlayer Stop and Play
Upvotes: 0