如何在单个视图中重复播放两个不同的本地视频

时间:2019-02-25 04:46:51

标签: ios swift avplayer

我正在使用单个视图中的两个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
                }
            }
        }
    }
  }
})

0 个答案:

没有答案