Reputation: 167
I made an android application where you can click buttons to play sounds. Every time, you click the button, a new MediaPlayer is getting created and the problem is, when you push a button during another sound is still playing, they are playing at the same time, but I want, that the previous sounds stops when you push a button. I already tried this code but my application crashes every time I press the button:
MediaPlayer mp;
Button button;
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
Is there a way to solve my problem?
Upvotes: 1
Views: 2438
Reputation: 327
@Override
public void onClick(View v) {
if(mp != null) {
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
Upvotes: 0
Reputation: 167
It seems like starting too many MediaPlayer isn't good, because when i click the sounds a couple times, the app crashes. I already changed mp.start to mp.reset and release.
Upvotes: 0
Reputation: 1476
It might be crashing because 'mp' is not initialized. Try this:
@Override
public void onClick(View v) {
//if mp exists and is playing...
if(mp != null && mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
EDIT You could also avoid checking for null by initializing 'mp' when you declare it on top.
For instance, instead of checking if mp != null. Change your declaration of 'mp' from:
MediaPlayer mp;
to
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
and your onclick method could look like:
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
}
//start mp from beginning
}
Upvotes: 2