AVPlayerLayer不播放视频,但音频很好

时间:2019-12-26 03:51:05

标签: swift avplayer avplayerlayer

我有一个令人困惑的问题。 我在课堂上声明了这些变量:

var audioPlayer = AVPlayer()
var videoPlayer = AVPlayer()
var videoLayer = AVPlayerLayer()

我有以下代码用于添加videoPlayer的容器:

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.

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

1 个答案:

答案 0 :(得分:0)

这很简单。早期,您说:

videoPlayerContainerView.layer.addSublayer(videoLayer)

好的,因此您有一个播放器层videoLayer,该播放器层没有任何播放器,并且现在在界面中。很好

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

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

那到底发生了什么?您在videoLayer中放弃了对先前添加到界面中的图层的引用,并用它替换了刚刚创建的全新播放器图层,该界面在界面中为 not 。好的,因此您与播放器关联的视频层不在界面中,因此您可以听到播放器,但看不到任何东西。

相关问题