AVPlayerLayer显示黑屏,但声音正常 [英] AVPlayerLayer shows black screen but sound is working

查看:641
本文介绍了AVPlayerLayer显示黑屏,但声音正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 AVPlayerLayer 中显示本地录制的视频,该视频有时 。我可以听到录制视频中的音频但看不到视频。有时视频和音频都有效,有时只有音频。

Im trying to display a local recorded video in a AVPlayerLayer which works sometimes. I can hear the audio from the recorded video but can't see the video. Sometimes both video and audio is working, sometimes only audio.

我已尝试使用 AVPlayerLayer AVPlayerViewController ,但两种情况都会出现同样的问题。所以这不是因为帧错误。

I've tried both with a AVPlayerLayer and AVPlayerViewController but the same issue occurs in both cases. So it's not because of the frames being wrong.

示例代码 AVPlayerViewController

let player = AVPlayer(url: url)
let playerController = AVPlayerViewController()
playerController.player = player

self.present(playerController, animated: true) {
  player.play()
}

示例代码 AVPlayerLayer

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!)

编辑1:

观察时播放器的状态,错误 nil 并且状态 readyToPlay

When observing the status of the player, error is nil and the status is readyToPlay

编辑2:

如果URL是远程的,则工作正常。

Works fine if the URL is remote.

编辑3:

如果我在视频完成导出后等待几秒钟,似乎可以正常工作。是不是100%写入文件系统的文件?

Seems to work if I wait a couple of seconds after the video has completed the export. Could it be something to have with the file not 100% written to the filesystem?

编辑4:
视频的问题,在这种情况下它播放了第3次。

Edit 4: Video of the problem, in this case it played the 3rd time.

推荐答案

以下是我设置视频工作的AVPlayerLayer的方法(我认为你缺少的是 videoGravity 参数)。

Here's how I set a AVPlayerLayer with the video working (I think what you're missing is 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()

这篇关于AVPlayerLayer显示黑屏,但声音正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆