我一直在寻找如何正确实现这一点。我看过here和 here 。并使用了最上面的答案 here ,为了尝试实现这一点,但对我来说,录制的视频甚至没有开始循环。第一帧显示但不播放视频,因此我想知道出了什么问题。
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if (error != nil) {
print("Error recording movie11: \(error!.localizedDescription)")
} else {
isSettingThumbnail = false
let videoRecorded = outputURL! as URL
playRecordedVideo(video: videoRecorded)
if !captureSession.isRunning {
DispatchQueue.global(qos: .background).async {
self.startRunningCaptureSession()
}
}
}
}
上述方法中使用的函数如下。
func playRecordedVideo(video: URL) {
thumbImage = nil
playerQueue = AVQueuePlayer(playerItem: AVPlayerItem(url: video))
playerLayer = AVPlayerLayer(player: playerQueue)
playerLayer.frame = (camBaseLayer?.bounds)!
playerLayer?.layoutIfNeeded()
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.isHidden = false
camBaseLayer?.layer.insertSublayer(playerLayer, above: previewLayer)
playerItem1 = AVPlayerItem(url: video)
playerLooper = AVPlayerLooper(player: playerQueue, templateItem: playerItem1)
self.playerQueue?.play()
}
我在上面的函数中尝试了以下操作:
var num = 0
if num == 0 {
self.playerQueue?.play()
num+=1
} else {
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerQueue.currentItem, queue: nil, using: { (_) in
DispatchQueue.main.async {
self.playerQueue.seek(to: CMTime.zero)
self.playerQueue.play()
}
})
}
但这只会导致视频在出现时甚至无法播放。
目标是防止视频循环时出现“间隙”
更新:
好吧,实际上变量 num 应该在函数之外,这将使 NS 代码运行,但最终会像以前一样卡住 View 。
更新2:
到目前为止我还没有找到解决方案。但可以肯定的是
` NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerQueue.currentItem, queue: nil, using: { (_) in
DispatchQueue.main.async {
self.playerQueue.seek(to: CMTime.zero)
self.playerQueue.play()
}
})
` 导致视频甚至不循环。有什么原因会发生这种情况吗?
最佳答案
几年前我使用这段代码做了同样的事情:
var player: AVPlayer!
var playerLayer: AVPlayerLayer!
private func playVideo(name: String) {
guard let path = Bundle.main.path(forResource: name, ofType:"mp4") else { return }
player = AVPlayer(url: NSURL(fileURLWithPath: path) as URL)
playerLayer = AVPlayerLayer(player: player)
self.playerLayer.frame = SOME_BOUNDS
self.player!.play()
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
}
@objc func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
self.playerLayer.removeFromSuperlayer()
playVideo(name: "SOME_NAME")
}
希望这能让您找到所需的功能
关于ios - 尝试无缝循环 AVPlayer (userCapturedVideo) 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53717624/