Im trying to make a video loop from an mp4 file. Like in the boomerang from instagram app, I have this code
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
}
}
But when the video reverse, it doesn 't look smooth and the reverse doesn' t start from the last part of the video. Any Ideas how to solve this? I want the video to look smooth like in the boomerang app loop