AVPlayerLayer shows a black screen, but the sound works

Im trying to display a local recorded video in AVPlayerLayer , which sometimes works. I hear the sound from the recorded video, but I do not see the video. Sometimes both video and audio work, sometimes only audio.

I tried working with AVPlayerLayer and AVPlayerViewController , but in both cases the same problem occurs. So this is not due to incorrect frames.

AVPlayerViewController sample code:

let player = AVPlayer(url: url) let playerController = AVPlayerViewController() playerController.player = player self.present(playerController, animated: true) { player.play() } 

AVPlayerLayer sample code:

 let asset = AVAsset(url: url) let item = AVPlayerItem(asset: asset) self.player = AVPlayer(playerItem: item) self.player?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil) self.playerLayer = AVPlayerLayer(player: self.player!) self.playerLayer?.frame = imageView.bounds imageView.layer.addSublayer(self.playerLayer!) 

Change 1:

When observing the player’s state, the error is nil , and the status is readyToPlay

Edit 2:

Works great if the URL is removed.

Edit 3:

It seems to work if I wait a couple of seconds after the export of the video is complete. Can there be something with a file that is not 100% written to the file system?

Edit 4: Video problems, in which case he played a third time.

+1
source share
2 answers

This is how I installed AVPlayerLayer with working video (I think you are missing the videoGravity parameter).

 let bundle = Bundle.main let moviePath = bundle.path(forResource: "myVideo", ofType: "mp4") let moviePlayer = AVPlayer(url: URL(fileURLWithPath: moviePath!)) playerLayer = AVPlayerLayer(player: moviePlayer) playerLayer.frame = movieView.bounds playerLayer.videoGravity = AVLayerVideoGravityResizeAspect movieView.layer.addSublayer(playerLayer) playerLayer.player?.play() 
+1
source

Is the height or width of the frame equal to zero

0
source

All Articles