尝试无缝循环AVPlayer(userCapturedVideo)时出现问题

时间:2018-12-11 05:00:11

标签: ios iphone swift avfoundation avplayer

我一直在寻找有关如何正确完成此操作的时间。我看过herehere。并使用最高答案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代码运行,但最终像以前一样冻结视图。

更新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()
                }
            })

` 导致视频甚至无法循环播放。为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

几年前,我使用这段代码做了同样的事情:

        Locale myLocale = new Locale("language_code");
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

希望这会指向您想要的功能