声明两个对象,avplayer是播放器,avplayeritem是播放条目信息
var player:AVPlayer?
var playerItem:AVPlayerItem?
let url = URL(string: "xxxx")! //设置播放的URL
playerItem=AVPlayerItem(url: url!)
player=AVPlayer(playerItem: playerItem)
player?.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: DispatchQueue.main, using: { (time) in
//这里可以处理播放进度,queue最好换成其他线程进行计算,然后在mainqueue中更新ui
}
self.playerItem?.addObserver(self, forKeyPath: "status", options: [.initial,.new], context: nil)//观察状态
self.playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.initial,.new], context: nil)//观察缓冲进度
self.playerItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: [.initial,.new], context: nil)//缓存可以播放的时候调用
处理观察者
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if "status"==keyPath{
switch player!.currentItem!.status {
case .readyToPlay:
//当前可播放,可以选择立即播放
player?.play()
case .unknown:
//尚未获取媒体信息
case .failed:
//不可播放
//player?.currentItem?.error可查看错误
}
}else if "loadedTimeRanges"==keyPath{
//当前缓冲进度
}else if "playbackLikelyToKeepUp"==keyPath{
//是否可播放
}
可用seek方法跳转指定位置播放。