AVPlayerLayer 不播放视频但音频很好

AVPlayerLayer not playing video but the audio is good

我有点困惑。 我在 class:

中声明了这些变量
var audioPlayer = AVPlayer()
var videoPlayer = AVPlayer()
var videoLayer = AVPlayerLayer()

我有这些用于添加视频播放器容器的代码:

let aspectHeight = view.frame.width * 9/16
let viewFrame = CGRect(x: 5, y: 0, width: view.frame.width - 10, height: aspectHeight)
let layerFrame = CGRect(x: 0, y: 0, width: view.frame.width - 10, height: aspectHeight)

videoPlayerContainerView.frame = viewFrame
videoPlayerViewController.frame = viewFrame
videoLayer.frame = layerFrame

videoLayer.backgroundColor = UIColor.green.cgColor
videoPlayerContainerView.layer.addSublayer(videoLayer)
videoPlayerContainerView.addSubview(videoPlayerViewController)

videoElementContainerView.addView(newView: videoPlayerContainerView)

我也有这个功能(我把传递的参数换成了临时的URL):

@IBAction func pausePlayVideo(_ sender: CustomButton) {
    let videoString = videoSourceURL + (sender.paramaters["thisVideoURL"] as! String)
    let videoURL = URL(string: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
    videoPlayer = AVPlayer(url: videoURL!)
    videoLayer = AVPlayerLayer(player: videoPlayer)

    videoPlayer.play()
}

我在这里调用它:

pausePlayButton.addTarget(self, action: #selector(ModuleLessonElementsViewController.pausePlayVideo(_:)), for: .touchUpInside)
pausePlayButton.paramaters["thisVideoURL"] = content

视图如下: The layer was added, the audio plays but the video does not.

按下按钮时,会播放音频,但不会播放视频。我在这里错过了一些重要的东西吗?

很简单。早些时候,你说:

videoPlayerContainerView.layer.addSublayer(videoLayer)

好的,所以你有一个播放器层 videoLayer,没有关联任何播放器,它现在在界面中。很好

稍后,当按下按钮时,您说:

@IBAction func pausePlayVideo(_ sender: CustomButton) {
    // ...
    videoLayer = AVPlayerLayer(player: videoPlayer)
    videoPlayer.play()
}

所以刚刚发生了什么?您在 videoLayer 中丢弃了对您之前添加到界面的层的引用,并用您刚刚创建的全新播放器层取而代之,即 not在界面中。好的,所以您与播放器关联的视频层不在界面中,因此您可以听到播放器但看不到任何东西。