I have a ListView and when I click on a row I play a sound.
If a sound is playing and I click on another row the first one should stop and the second start.
If I don’t release the MediaPlayer the application crashes, but this delays the execution of the next sounds.
What I’m doing wrong? This is my code:
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(!isPlaying){
mPlayer = MediaPlayer.create(this,soundid[position]);
mPlayer.start();
isPlaying = true; // reproducir es true
}else{
isPlaying = false;
mPlayer.stop();
mPlayer.reset();
mPlayer = MediaPlayer.create(this,soundid[position]);
mPlayer.start();
isPlaying = true;
}
mPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mPlayer) {
mPlayer.release();
isPlaying = false;
}
});
}
In this type of implementation you are creating several instances of media player and not releasing them can cause an exception (refer here). I would suggest you to re-use the already existing media player instance. You can accomplish your goals by doing something like this.