2

如何从 AVPlayer 获取视频的视频大小以设置节点的几何大小?

例如,我有一个宽度和高度的 SCNPlane

let planeGeo = SCNPlane(width: 5, height: 5)

所以现在我实例化我的视频播放器

let videoURL = NSURL(string: someURL)
let player = AVPlayer(URL: videoURL!)

和我的 SKVideoNode

let spriteKitScene = SKScene(size: CGSize(width: 1920, height: 1080))
spriteKitScene.scaleMode = .AspectFit

videoSpriteKitNode = SKVideoNode(AVPlayer: player)
videoSpriteKitNode.anchorPoint = CGPointMake(0,0)
videoSpriteKitNode.size.width = spriteKitScene.size.width
videoSpriteKitNode.size.height = spriteKitScene.size.height

spriteKitScene.addChild(videoSpriteKitNode)

planeGeo!.firstMaterial.diffuse.contents = spriteKitScene
videoSpriteKitNode.play()

所以现在我想让视频大小将我的飞机调整为正确的纵横比。我已经摆弄了 AVLPlayerLayer 但这给了我总是 0

let avLayer = AVPlayerLayer(player: player)
print(avLayer.videoRect.width) //0
print(avLayer.videoRect.height) //0

我也在这里尝试过,但效果不佳

let avLayer = AVPlayerLayer(player: player)
let layer = avLayer.sublayers![0]
let transformedBounds = CGRectApplyAffineTransform(layer.bounds, CATransform3DGetAffineTransform(layer.sublayerTransform))
print(transformedBounds.width) //0
print(transformedBounds.height) //0
4

1 回答 1

1

好的,我想通了,KVO 是要走的路。在 viewDidLoad 中添加:

player.currentItem?.addObserver(self, forKeyPath: "presentationSize", options: .New, context: nil)

在 deinit 中:

player.currentItem?.removeObserver(self, forKeyPath: "presentationSize")

然后添加:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

    if keyPath == "presentationSize" {
        if let item = object as? AVPlayerItem {
            let size = item.presentationSize
            let width = size.width
            let height = size.height

            //Set size of geometry here
        }
    }
}
于 2016-02-07T23:13:29.720 回答