How to Add an Action upon Audio Play Completion
MediaPlayer.OnCompletionListener was added in API Level 1
Interface definition for a callback to be invoked when playback of a media source has completed.
1. Create a MediaPlayer for the Audio Resource named myMediaPlayer.
MediaPlayer.OnCompletionListener was added in API Level 1
Interface definition for a callback to be invoked when playback of a media source has completed.
1. Create a MediaPlayer for the Audio Resource named myMediaPlayer.
2. In the MainActivity.java file, add the code below to the imports section.
import android.media.MediaPlayer.OnCompletionListener;
import android.widget.Toast; //Needed for testing purposes only
3. In the onCreate method, add the below code. I add a Toasts for testing purposes only.
if (mediaPlayer != null) { //make sure the media player exists
Toast.makeText(this, "myMediaPlayer Created", Toast.LENGTH_SHORT).show();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer ocMediaPlayer) {
//add your code here
//add your code here
Toast.makeText(getBaseContext(), "MediaPlayer OnCompletionListener Invoked", Toast.LENGTH_SHORT).show();
}
});
4. Compile and run!
5. Now, Play the Audio to invoke the onCompletionListener.
6. Good practice is to release the MediaPlayer in the OnCompletionListener.
Note: It is not necessary to call if (myMediaPlayer != null) in OnCompletionListener, as it will not fire.
It is not necessary to call if (myMediaPlayer.isPlaying()) in OnCompletionListener, as it will not fire.
Therefore, if it is not playing, then you do not need to call myMediaPlayer.stop() in OnCompletionListener, as it will not necessary, as it is already stopped.
Related Articles:
Resources:
http://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html