Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting end of the playback in AVAudioPlayer

I've got couple of short .mp3 sounds which I'm storing in the array and would like to play them consecutively. Is there any way to detect when AVAudioPlayer stopped playing so that I could call a completion handler and play next sound? I know that there is a delegate for that but I'm using Playground and SKScene.

like image 313
mikro098 Avatar asked Sep 15 '25 02:09

mikro098


1 Answers

Hellp @codddeer123,

AVAudioPlayer contains AVAudioPlayerDelegte method which is called on audio playing completed.

I have implemented it as extension of my class, you can do as you likes.

extension MyViewController: AVAudioPlayerDelegate {

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            // After successfully finish song playing will stop audio player and remove from memory
            print("Audio player finished playing")
            self.audioPlayer?.stop()
            self.audioPlayer = nil
            // Write code to play next audio.
        }
    }
}

You can write your code here to play next audio. As per your question I have posted this answer. If you don't know about AVAudioPlayer then go for apple official documentation or other online tutorials.

I hope this will help you.

like image 67
Sagar Chauhan Avatar answered Sep 16 '25 17:09

Sagar Chauhan