Luke
Luke

Reputation: 2486

Swift - AVFoundation - Inspect Video Dimensions/Aspect Ratio

I have an iOS app which at the moment simply plays a video using AVFoundation from the user's library. What I would like to do is to set the orientation of the device based on the aspect ratio of the video. If it is a portrait video, I would like to set the orientation to portrait, if standard 16:9 or 4:3, then of course landscape, so that the screen doesn't end up with a lot of wasted space in black bars either side of the video.

I figured I could determine the aspect ratio and thus the orientation by getting the dimensions of the video:

if width > height:
    landscape
else:
    portrait

However, this is proving more difficult than I had imagined. I have an AVPlayer object and initially looked into its metadata property, but this apparently doesn't seem to be the sort of metadata I am after. Then I found that AVPlayer.presentationSize can have the info I'm looking for but when I printed that out - right before calling play() - to have a look at it I got the following: Optional((0.0, 0.0))

Short of looking into how I can parse the video file headers myself to try to access this info, is there anywhere in the APIs where this is exposed to me? Googling comes up with a lot of info about how to specify the size of a video when capturing one, but not much if anything about this particular problem.

Upvotes: 0

Views: 915

Answers (1)

Frank Rupprecht
Frank Rupprecht

Reputation: 10418

You can ask the underlying asset for its size:

let asset = player.playerItem.asset
let videoTrack = asset.tracks(withMediaType: .video).first!
let naturalSize = videoTrack.naturalSize
let transform = videoTrack.preferredTransform
let size = naturalSize.applying(transform)

Upvotes: 6

Related Questions