为 SceneKit 中的 SKVideoNode 确定 size/aspect 视频比例

Determine size/aspect ratio of video for SKVideoNode in SceneKit

如何从 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

好的,我明白了,KVO 是正确的选择。在viewDidLoad中添加:

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

在初始化中:

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
        }
    }
}