I am trying to loop a video with playerViewController on Swift for TVOS. I have the video playing fine, but I want to loop the video. Here is my code so far:
override func viewDidAppear(_ animated: Bool) {
let videoURL = URL(string: "https://url-to-video.com/video.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
Any help is appreciated. Thanks
The quickest way to do this is to use an AVQueuePlayer with an AVPlayerLooper. You can set the player on your player view controller the same as you would with an ordinary AVPlayer, but you need to keep a persistent reference around to the looper so it’ll keep working. In other words, add this to your view controller’s interface:
var looper: AVPlayerLooper?
…and in your viewDidAppear
, replace this:
let player = AVPlayer(url: videoURL!)
with this:
let player = AVQueuePlayer()
looper = AVPlayerLooper(player: player, templateItem: AVPlayerItem(asset: AVAsset(url: videoURL!)))
Then, once you start the player playing, its video will loop indefinitely.