OStack程序员社区-中国程序员成长平台

标题: ios - 制作像回旋镖一样的视频循环效果 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:22
标题: ios - 制作像回旋镖一样的视频循环效果

我正在尝试从 mp4 文件制作视频循环。就像 instagram 应用程序的回旋镖一样,我有这个代码

class ViewController: UIViewController {

    var avPlayer: AVPlayer!
    var avPlayerLayer: AVPlayerLayer!
    var paused: Bool = false
    var reverse: Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
        let theURL = Bundle.main.url(forResource:"vidio", withExtension: "mp4")

        avPlayer = AVPlayer(url: theURL!)
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        avPlayer.volume = 0
        avPlayer.actionAtItemEnd = .none

        avPlayerLayer.frame = view.layer.bounds
        view.backgroundColor = .clear
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        NotificationCenter.default.addObserver(self,
                                               selector: #selector(playerItemDidReachEnd(notification),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                               object: avPlayer.currentItem)
    }

    func playerItemDidReachEnd(notification: Notification) {

        guard reverse else {
            avPlayer.seek(to: kCMTimeZero)
            avPlayer.rate = 1.0
            reverse = true
            print("normal")
            return
        }

        print("reversa")

        avPlayer.seek(to: avPlayer.currentItem!.duration,
                    toleranceBefore: kCMTimeZero,
                    toleranceAfter: kCMTimeZero)
        avPlayer.rate = -1.0

        reverse = false
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        avPlayer.play()
        paused = false
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        avPlayer.pause()
        paused = true
    }
}

但是当视频反转时,它看起来并不流畅,并且反转不是从视频的最后部分开始的。任何想法如何解决这个问题? 我希望视频看起来像在回旋镖应用循环中一样流畅



Best Answer-推荐答案


我建议使用图像而不是视频,因为您可以创建一组图像,然后循环遍历它们以获得相同的效果,但难度较小。

关于ios - 制作像回旋镖一样的视频循环效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359634/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4