我正在使用单个视图中的两个AVPlayer
对象播放两个不同的本地视频。并且这两个视频将使用AVPlayerItemDidPlayToEndTime
通知重复播放。
@objc private func playerItemDidReachEnd() {
if let player = assetPlayer {
player.seek(to: kCMTimeZero)
player.play()
}
}
现在问题是AVPlayerItemDidPlayToEndTime
通知调用了4次,并且一段时间后AVPlayerItemDidPlayToEndTime
通知不断调用了(我的假设是视频卡住了末尾,所以它不断调用通知),这导致崩溃应用。
这是我的代码:
let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
var urlAsset = AVURLAsset(url: url, options: options)
guard let asset = urlAsset else { return }
asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
DispatchQueue.main.async {
var error: NSError?
let status: AVKeyValueStatus = asset.statusOfValue(forKey:"tracks",error: &error)
if status == AVKeyValueStatus.loaded {
assetDuration = CMTimeGetSeconds(asset.duration)
let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
var playerItem = AVPlayerItem(asset: asset)
if let item = playerItem {
item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
if let output = videoOutput {
item.add(output)
item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
assetPlayer = AVPlayer(playerItem: item)
if let player = assetPlayer {
player.rate = 1.0
}
if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
layer.player = assetPlayer
}
}
}
}
}
})