I am making an app that plays sound that a user chooses. first they select the category, then they choose a specific sound. the sounds are not very long, currently the app will play sounds just fine. however if the user selects one sound and then they select a second sound to play the 2 sounds will overlap(the beta testers find this annoying apparently). I have tried both media player and sound pool. After researching the issue I discovered that the likely cause of the overlap is that I use mp = mediaplayer.create(this,raw.soundfile); mp.start()
to play each sound. I have since tried to alter how the sound in played. After reading several posts including this tutorial below is the relevant code I currently have
public class [classname] implements [something] extends[somethingelse]{
MediaPlayer mp; //moved out of play sound method
protected void OnCreate(Bundle savedInstanceState){
mp = new MediaPlayer();// added to this area
}
public void playSound (View view) {
if (mp.isPlaying() ){
mp.stop();
mp.release();
}
switch (selection) {
case "sound1":
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
break;
case "sound2":
mp = MediaPlayer.create(this, R.raw.sound2);
mp.start();
break;
case "sound3":
mp = MediaPlayer.create(this, R.raw.asound3);
mp.start();
break;
**10 more cases in this playsound method**
After some trial and error and help from Udi Idan the above code is what is currently working in my app.
If you want to avoid the overlapping, you should check weather a sound is playing and stop it:
if (mp != null && mp.isPlaying())
mp.pause();
And then play the new sound.
Edit
You should be consistent with the way you play the sound.
Create one MediaPlayer variable as class member:
MediaPlayer mp;
if (mp != null && mp.isPlaying()){
mp.stop();
}
switch (selection) {
case "sound1":
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
break;
case "sound2":
mp = MediaPlayer.create(this, R.raw.sound2);
mp.start();
break;
case "sound3":
mp = MediaPlayer.create(this, R.raw.sound3);
mp.start();
break;
}