我有一个使用AVPlayerAVPlayerLayer(Swift,iOS 8.2)播放的本地视频,并且在调整其父 View (AVPlayerLayer)的大小(包括方向更改)时,需要调整introPlayerLayer(introView)的大小。到目前为止,我尝试过的所有操作似乎都无效,并且playerLayer的大小和位置错误。

使用本地mp4视频设置AVPlayer,并使用该播放器初始化AVPlayerLayer。然后将该层作为子层添加到父 View 。

这是我的代码:

func playIntro() {
    let path = NSBundle.mainBundle().pathForResource("intro", ofType: "mp4")
    let url  = NSURL.fileURLWithPath(path!)
    let introPlayer           = AVPlayer(URL: url)
    introPlayer.allowsExternalPlayback = false

    var introPlayerLayer = AVPlayerLayer(player: introPlayer)
    introView.layer.addSublayer(introPlayerLayer)
    introPlayerLayer.frame = introView.bounds

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: introPlayer.currentItem)

    introView.hidden = false
    introPlayer.play()
}

我应该将AVPlayerLayer作为UIView的子层添加,还是应该对父容器(UIView)进行子类化,如https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html的“播放器 View ”部分所示。如果是这样,我将如何在Swift中编写PlayerView子类(在Objective-C中显示)?
预先感谢您的协助。

最佳答案

swift 3。

private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        var playerLayer: AVPlayerLayer?
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        playerLayer!.frame = self.view.frame
        self.view!.layer.addSublayer(playerLayer!)
        player.play()

    }

关于ios - Swift:调整AVPlayerLayer的大小以匹配其父容器的边界,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29000251/

10-08 20:51