How do you detect when a sound file has finished?

AndroidWhile Loop

Android Problem Overview


I am playing a sound file using this code inside a broadcast receiver activity:

notification.sound = Uri.parse("android.resource://emad.app/raw/seven_chimes");

I would like to detect when this file has finished playing.

I tried a loop like this but I think this is only good for the media player because it always = false even though I made sure the sound file was still playing:

/*
 * Stay here until the chime sound is finished.
 */
   while (manager.isMusicActive()){
   }

Can you show me what I should use instead of manager.isMusicActive()?

Android Solutions


Solution 1 - Android

You can use the MediaPlayer class and add a Completion listener to be activated when the sound finishes playing

MediaPlayer mp = MediaPlayer.create(this,Uri.parse("android.resource://emad.app/raw/seven_chimes"));
    
mp.setOnCompletionListener(new OnCompletionListener() {
        	
    @Override
    public void onCompletion(MediaPlayer mp) {
        performOnEnd();
    }
        
});

mp.start();

Solution 2 - Android

Not working with broadcast receiver but this is what worked for my current project using Kotlin to track when the audio file has finished playing.

playButton.setOnClickListener {

            if (isPlaying) {
                pauseSound()
            }else {
                playSound()
            }

            mediaPlayer.setOnCompletionListener {
                playButton.text = "Play"
                isPlaying = false
            }
        }

isPlaying is boolean, I will explain more if someone is confused. Hope it helps someone else in the future. Happy coding!

Solution 3 - Android

try using service to play the music.. after it play once, then stop your service and you can add your program on the onDestroy() service method.. hope it helps :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmad-ud-deenView Question on Stackoverflow
Solution 1 - AndroidRonnyView Answer on Stackoverflow
Solution 2 - AndroidthesamoanppprogrammerView Answer on Stackoverflow
Solution 3 - AndroidMichael FransView Answer on Stackoverflow