swift. AVPlayer. How to track when song finished playing?

前端 未结 7 594
春和景丽
春和景丽 2021-01-30 13:51

What is the east way to track when song finished playing with AVPlayer in Swift?

Is there any function which is called when avplayer finished playing, or I should combin

7条回答
  •  执念已碎
    2021-01-30 14:36

    Something like this works:

    func play(url: NSURL) {
        let item = AVPlayerItem(URL: url)
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)
    
        let player = AVPlayer(playerItem: item)
        player.play()
    }
    
    func playerDidFinishPlaying(note: NSNotification) {
        // Your code here
    }
    

    Don't forget to remove the observer when you're done (or in deinit)!

提交回复
热议问题