Detect music finished playing

2k Views Asked by At

I have music that I play via

AssetFileDescriptor assetDescriptor = getAssets().openFd(filename);
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(), assetDescriptor.getStartOffset(), assetDescriptor.getLength());
mediaPlayer.prepareAsync();
mediaPlayer.setVolume(1, 1);
mediaPlayer.start();

How should I detect if this music stopped playing so that I can start playing next one?

I have tried constantly checking (once every second), via

((AudioManager) application.getSystemService(Context.AUDIO_SERVICE)).isMusicActive();

But that doesn't seem to work(always returns true). Is there any other means for me to be notified of the music stopped playing so that I can start the next one?

2

There are 2 best solutions below

0
On BEST ANSWER

Use MediaPlayer.onCompletionListener to listen to the event when a track ends. The next audio file will play after this. An example

player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer player) {
        player.stop();
        // next audio file
    }
 });
 player.start();

An added recommendation, to play multiple audios on after another, you don't have to create nested onCompletionListener. Instead use the below code.

int[] myAudio = {R.raw.audio1, R.raw.audio2, R.raw.audio3};
int mTrackFinish = 0;
MediaPlayer mp = MediaPlayer.create(this, myAudio[0]);
mp.setOnCompletionListener(new OnCompletionListener() 
{
@Override
public void onCompletion(MediaPlayer mp)
{
 mTrackFinish++;
 mp.reset();
 if(mTrackFinish < myAudio.length)
        // play some audio from list
    else
      mTrackFinish=0;
      mp.release();
      mp = null;  // either set counter to 0 and start again or call end of list

}
});
mp.start();
0
On

MediaPlayer has a method called setOnCompletionListener, which does the following:

Register a callback to be invoked when the end of a media source has been reached during playback.

For more information: https://developer.android.com/reference/android/media/MediaPlayer.html#setOnCompletionListener%28android.media.MediaPlayer.OnCompletionListener%29