Search code examples
javaandroidandroid-mediaplayerandroid-audiomanager

Sound stopping after some time - Android


This code is called everytime I click a button. After some time when I click the button, the sound is not displayed anymore. I tried to use another music file, and also I tried to use the MediaPlayer instead of SoundPool, but the problem kept happening.

To be more specific about the problem, it is like: I click for 10 times and it is returning the sound, when I click once again it stops

public void displaySound(Context context){
        SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        int soundId = sp.load(context, R.raw.bubble_nice, 1);
        sp.play(soundId, 1, 1, 0, 0, 1);
        MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.bubble_nice);
        mPlayer.start();
    }

When the sound stops, this is appearing in the log: E/MediaPlayer: error (1, -19)


Solution

  • I have tried your code and found a solution, you can try as follow:

    first declare a mediaplayer object gloabally like

    MediaPlayer mPlayer;
    

    then use following method on click of button.

     public void displaySound(Context context) {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.stop();
            mPlayer.reset();
        }
        mPlayer = MediaPlayer.create(context, R.raw.bubble_nice);
        mPlayer.start();
    }