Pregunta

How do i use the OnCompletionListener for two mediaplayers playing at the same time?

The application allow users to play two media : Recorded track and Music track at the same time if one of them stops the other should stop too. I found solutions about how to apply on Completion Listener for single MediaPlayer.

My first approach was to declare two listener for each media :

mp0.setOnCompletionListener(cplmp0);

mp1.setOnCompletionListener(cplmp1);

private MediaPlayer.OnCompletionListener cplmp0 = new MediaPlayer.OnCompletionListener() {

    public void onCompletion(MediaPlayer m) {


        mButtonListenOriginal.setImageResource(R.drawable.player_button_listen);

        mp1.stop();
        mp1.reset();
    }
}
private MediaPlayer.OnCompletionListener cplmp1 = new MediaPlayer.OnCompletionListener() {

    public void onCompletion(MediaPlayer m) {

        mp0.stop();
        mp0.reset();
    }
}

Is this a good practice to do? Is there any other solutions?

¿Fue útil?

Solución

Anyways you dont need to check which player has been stopped, As you want to both player to be stop after any of the player completes playing. So simply add common listener to both players.

    mp0.setOnCompletionListener(cplmp);
    mp1.setOnCompletionListener(cplmp);

and stop both players

private MediaPlayer.OnCompletionListener cplmp = new MediaPlayer.OnCompletionListener() {

    public void onCompletion(MediaPlayer m) {

        if (mp0 != null) {
            mp0.stop();
            mp0.reset();

        }
        if (mp1 != null) {
            mp1.stop();
            mp1.reset();
        }
    }

};

Otros consejos

For a better readability, you can implement the listener to your class and set both players' listeners your class. Then in your overrided onCompletition method, you can make an if control for both of your players,

if(m == mp0) {
..
..
}
else if(m == mp1){
..
..
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top