ios avplayer 监控播放进度

 

 

 

 

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)

  

posted @ 2019-12-05 15:53  荣超  阅读(3564)  评论(0编辑  收藏  举报