Search code examples
javaandroidaudio-playerandroid-music-player

mp3 stops playing after it worked a few times?


I have a program that plays a short, 1 sec. .mp3 sound on every buttonclick (every time a different sound). After clicking the buttons a few times, the sound suddenly stops at all for the whole program, I have another background sound on another activity, If I start this activity after no sound is coming anymore, no sound is coming on this activity either.

code example of the buttonclickers:

mp1 = MediaPlayer.create(this, R.raw.s1);
mp2 = MediaPlayer.create(this, R.raw.s2);
i++;

if (i == 1) {
    mp1.start();
}

if (i == 2) {
    mp2.start();
}

Solution

  • Make sure you reset and release your media player when it is done playing!

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.reset();
            mediaPlayer.release();
        }
    });
    

    Also reset the integer variable.

    if(i == 2){
       i = 0;
    }