2012-04-01 21 views
16

¿Cómo uso el oyente OnCompletion para escuchar música? Me gustaría presionar un botón para ir a otra actividad que reproduce algo de música y luego regresa cuando termina la reproducción de música. Ya he codificado las otras cosas. Simplemente no puedo entender cómo usar el oyente OnCompletion?OnCompletion oyente con MediaPlayer

Respuesta

32

Usted debe poner el código que debe ejecutarse cuando la música se completa en el OnCompletionListener, por ejemplo:

mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    public void onCompletion(MediaPlayer mp) { 
     finish(); // finish current activity 
    } 
}); 
+0

Solución perfecta, funcionó para mí – Pitto

+0

Muchas gracias !!! Funcionó :) –

6
mPlayer.setOnErrorListener(new OnErrorListener() { 
public boolean onError(MediaPlayer paramMediaPlayer, int paramInt1,int paramInt2) { 
// TODO Auto-generated method stub 
//your code if any error occurs while playing even you can show an alert to user 
return true; 
} 
}); 
mPlayer.setOnCompletionListener(new OnCompletionListener() { 
public void onCompletion(MediaPlayer mp) { 
// TODO Auto-generated method stub 
//your code if the file was completely played either show an alert to user or start another activity or file. 
//even you can finish you activity here 
}     
}); 
4

encuentro que anteriores son correctas sin embargo he tenido problemas en dónde colocar el código. ¡A continuación, coloco este código después de mi código para comenzar la canción!

playButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    mediaPlayer.start();  //Next line is the beginning of where to place the code. 
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mediaPlayer) { 
     Toast.makeText(MainActivity.this, "I'm Finished", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    } 
}); 
Cuestiones relacionadas