I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me. Here is my Activity:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset();
}
else {
mpButtonClick1.start();
}
}
});
When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception
In some editions of Windows 10, it's included as an optional feature that you can enable. To do that, select the Start button, then select Settings > Apps > Apps & features > Manage optional features > Add a feature > Windows Media Player, and select Install.
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network.
1 Answer. Show activity on this post. MediaPlayer has an OnCompletionListener callback you can register to get notified when playback stops.
Try to use pause
instead of stop
.
Reason: if you pause the MediaPlayer
, then you can resume it later. However, if you use stop
, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).
More info: here and here
PS: don't forget to release the memory when you finish using the resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With