How to detect when AVPlayer video ends playing?

前端 未结 10 958
感动是毒
感动是毒 2020-11-28 07:48

I\'am using AVPlayer for playing local video file (mp4) in Swift. Does anyone know how to detect when video finish with playing? Thanks

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 08:37

    I know there are a lot of accepted answers here...

    But, another route might be to add a boundary time observer to your AVPlayer. You would have to have the duration of the video, which you can get from your player.currentItem, and then add it as your desired time boundary.

    fileprivate var videoEndObserver: Any?
    
    func addVideoEndObserver() {
        guard let player = YOUR_VIDEO_PLAYER else { return }
    
        // This is just in case you are loading a video from a URL.
        guard let duration = player.currentItem?.duration, duration.value != 0 else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
                self?.addVideoEndObserver()
            })
    
            return
        }
    
        let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
        videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
            self.removeVideoEndObserver()
    
            // DO YOUR STUFF HERE...
        })
    }
    
    func removeVideoEndObserver() {
        guard let observer = videoEndObserver else { return }
    
        videoPlayer.player?.removeTimeObserver(observer)
        videoEndObserver = nil
    }
    

提交回复
热议问题