1

I'm trying to get a video to play in my macOS project and I want it to continuously loop. I was able to get it to play once but I can't figure out how to get it to loop. I'm using the AVPlayerLooper but seem to be messing up somewhere. Here is my code:

import Cocoa
import AVKit
import AVFoundation

class ViewController: NSViewController {

    @IBOutlet weak var videoPlayer: AVPlayerView!

    override func viewDidLoad() {
        //var loop: AVPlayerLooper?

        super.viewDidLoad()

        guard let path = Bundle.main.path(forResource: "Background", ofType:"mp4") else {
            debugPrint("Not found")
            return
        }

        let asset = AVAsset(url: URL(fileURLWithPath: path))
        let item = AVPlayerItem(asset: asset)
        let queuePlayer = AVQueuePlayer(playerItem: item)
        let loop = AVPlayerLooper(player: queuePlayer, templateItem: item)
        videoPlayer.player = queuePlayer
        videoPlayer.player?.play()
    }
}

I also have an AVPlayerView in my storyboard that I have connected to my viewcontroller.

It builds and runs fine but when I run it nothing shows up. I just get a black screen.

Any help is appreciated. Thanks!

Eric Walier
  • 331
  • 2
  • 18

1 Answers1

6
  • AVPlayerLoop is sort of a "top level" object that manages both the player and the player item. So you have to keep it around, e.g. in a custom property of the view controller, or it will be released before it can really do anything

  • Since AVPlayerLoop manages the items in the AVQueuePlayer, initialize the queue player without passing in the player item

NoHalfBits
  • 604
  • 1
  • 5
  • 10
  • I assigned it but now it's just playing once instead of looping. It gives me a warning "initialization of value loop was never used." I think this is where the problem lies but all the documentation I'm reading says that's all I need. I updated my code in the original post. – Eric Walier Dec 04 '18 at 02:44