Search code examples
swiftxcodeswift3avplayerswift-playground

How to call function when song finished in a Swift Playground


I'm trying to call a function when a song finishes playing in a Swift playground. This is the code I'm using:

NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: winMusic)

However the function isn't called when the song finishes playing, and I don't know why? It's obviously not the same as in an iOS app.

var winMusic = NSURL(fileURLWithPath: Bundle.main.path(forResource: "win", ofType: "mp3")!)
var winPlayer: AVAudioPlayer? = nil
class Responder : NSObject {
    func playerDidFinishPlaying() {
        print("test")
        /* Nothing printed here */
    }
    func action(sender: UIButton) {
        NotificationCenter.default.addObserver(self, selector: #selector(Responder.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: winMusic)
        NotificationCenter.default.post(name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        winPlayer!.play()
    }
}

Solution

  • Set your winPlayer delegate as,

    winPlayer?.delegate = self
    

    and implement the method

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag == true {
            // song finished successfully here
        }
    }
    

    where you will place the delegate is up to you.