MediaPlayer.create () stops working after some sounds [duplicate]

1

Hello, I put a different sound to touch each button pressed, but after 4 starts it simply stops.

Code:

 numero = random.nextInt(numeros.length);
 MediaPlayer soundID = MediaPlayer.create(this, getResources().getIdentifier("s" + numeros[numero], "raw", getPackageName()));
 soundID.start();

Error:

08-06 02:04:50.604 15072-15072/lordlokon.contarapp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
08-06 02:04:52.089 15072-15072/lordlokon.contarapp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
08-06 02:04:54.259 15072-15072/lordlokon.contarapp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
08-06 02:04:55.368 15072-15072/lordlokon.contarapp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
08-06 02:04:58.179 15072-15072/lordlokon.contarapp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
08-06 02:04:58.202 15072-15083/lordlokon.contarapp E/MediaPlayer: error (1, -19)
08-06 02:04:58.202 15072-15072/lordlokon.contarapp E/MediaPlayer: Error (1,-19)
    
asked by anonymous 06.08.2016 / 07:07

1 answer

1

Whenever you use MediaPlayer you should make the release of it after it has finished playing the sound.

In order to be notified of this occurrence, implement the OnCompletionListener interface and pass it to the MediaPlayer% method

//Atributo para guardar a referência ao *MediaPlayer*
private MediaPlayer soundID;

Change your code to:

//Se algum som ainda estiver a tocar pára-o
releasePlayer();

numero = random.nextInt(numeros.length);
soundID = MediaPlayer.create(this, getResources().getIdentifier("s" + numeros[numero], "raw", getPackageName()));

soundID.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        //No final de tocar liberta o media player para poder ser novamente utilizado
        releasePlayer()
    }
});

soundID.start();

Method to free MediaPlayer

private void releasePlayer() {
    if (soundID != null) {
        soundID.stop();
        soundID.release();
        soundID = null;
    }
}
    
06.08.2016 / 11:50