var timeObserver = avPlayerVC.player?.addPeriodicTimeObserver(forInterval: CMTime.init(value: 1, timescale: CMTimeScale(NSEC_PER_SEC)), queue: nil, using: {(cmtime) in let progress = cmtime.seconds / CMTimeGetSeconds(self.avPlayerVC.player!.currentItem!.duration) if (progress == 1.0) { //播放百分比為1表示已經播放完畢 print("播放完成") //處理播放完成之后的操作 clickblock() } })
上面需要在設置完成播放源之后執行,之前執行的話檢測不到進度
每次切換播放源最后先關閉舊的timeObserver 在重新開啟新的timeObserver
在關閉播放頁面時需要關閉 timeObserver 否者會閃退
avPlayerVC.player?.removeTimeObserver(timeObserver!)
增加播放時資源狀態監控
avPlayerVC.player?.currentItem.addObserver(self,forKeyPath:"status",options: .new,context:nil) override func observeValue(forKeyPath keyPath:String?,of object:Any?,change:[NSKeyValueChangeKey : Any]?,context:UnsafeMulableRawPointer?){ if(keyPath == "status"){ switch self.avPlayerVC.player?.curentItem?.status { case .readyToPlay: //准備好播放了 //ios10及以下版本 記住播放位置seek時需要在這里調用否者會閃退 print("可以在這里調用播放") case .unknown: //資源不存在 case .failed: //資源播放異常 } } } //關閉頁面時或者切換資源之前注銷 avplayerVC.player?.currentItem?.removeObserver(self,forKeyPath:"status",context:nil)