AVPlayer crashes at replaceCurrentItem

I am having big troubles in using AVAsset, AVPlayerItem and AVPlayer.


My goal is to create an Application on macOS which plays several different videos synchronously in one same window. As inspiration I am using an old Apple demo project called “AVMediaSelectionDemo” from 2013 which basically does that.


To get there, I wrote a small test application which has a window and its windowController with a placeholderView (for convenience reasons) and a button to choose a movie-file and get the whole thing started.


In the windowDidLoad() function of the windowController I create and add manually an instance of a PlaybackView into the placeholderView. So far everything works fine, but in my PlaybackView I stumble onto some problems, where I don’t see what I’m doing wrong. The stripped down code of the PlaybackView looks as follow:



import Cocoa
import AVFoundation

class PlaybackView: NSView {
   
   
    var asset: AVURLAsset?
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?
    var playbackDidBegin: Bool = false
   

   
    override init(frame frameRect: NSRect) {
        print("Playbackview init")
        super.init(frame: frameRect)
       
        self.layer = CALayer()
        self.wantsLayer = true
        self.layer?.backgroundColor = CGColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
       
        self.playbackDidBegin = false
    }
   
    required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
   
   
   
    func setupPlaybackUsingURL(_ url:URL) {
       
        asset = AVURLAsset(url: url)
        let playeritem = AVPlayerItem(asset: asset!)
       
        player = AVPlayer()
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.backgroundColor = CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
        playerLayer?.frame = self.bounds
        self.layer?.addSublayer(playerLayer!)
       
        player?.play()
       
        player?.replaceCurrentItem(with: playeritem)
    }
 
   
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
       
        // Drawing code here.
    }

}


Everything seems to work fine until I add line number 45


player?.replaceCurrentItem(with: playeritem)


at that moment the application crashes, and I don’t see why.


I would really appreciate some help in order to bring me forward with my project.


thanks in advance


greetings

Henri