Java – How to make android mediaplayer play sound

androidjavamedia-player

I don't know why it doesn't works, there is no error logged in logcat, but I cannot hear a sound.

public static void DeclararSonido(int numero, Context contexto){
    switch(numero){
    case 0:
        mp = MediaPlayer.create(contexto, R.raw.alan);
        break;          
    }
}

public static void TocarPiedra( int posicion, Context contexto){
    DeclararSonido(posicion, contexto);


    mp.start();
    mp.stop();
    mp.release();
}
public static void TocarSirena(Context contexto){
    MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);


    mp2.start();
    mp2.stop();
    mp2.release();

}

If I erase mp2.stop(); and mp2.release(); AND mp.stop(); and mp.release(); the app plays the sound, but the file is not released…

Best Solution

You certainly do not want to Start and then Stop right away..

The problem is that you are executing these right after each other:

mp.start();      // starts playback
mp.stop();       // .. then stops immediately ..
mp.release();

You should call start, and then when the sound is done playing, release. You can use the Completion event to hook up a listener and release there:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
    public void onCompletion(MediaPlayer player) {
       player.release();          
    }
})