Get the dimensions of video programmatically in objective c
You can read a video's dimensions using AVURLAsset
and AVAssetTrack
, like this:
NSURL *mediaURL; // Your video's URL
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:mediaURL options:nil];
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *track = [tracks objectAtIndex:0];
Then using the AVAssetTrack
's naturalSize property:
CGSize mediaSize = track.naturalSize;
The benefit of getting the video's metadata this way is that you can access it immediately, without having to play the video or waiting for it to load.
Just thought i'd share my experiences for those that find this page.
The natural size is not actually the encoded resolution, it's the display resolution. this can be different from the encoded resolution for example if the pixel aspect ratio != 1 or (more common) there's a clean aperture metadata information in the encoded video.
To get the encoded resolution the only way I've found is to decode the first frame with eg AVASsetReaderTrackOutput then inspect the resulting pixel buffer with CVPixelBufferGetWidth (or GetHeight) to get the data resolution. if you use imageGenerator you get the display resolution (and an rgb bitmap of the display resolution)
It takes time for the MPMoviePlayerController to load the video metadata, so you should add a listener and wait for the naturalSize to be loaded. Something like this:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(movieNaturalSizeAvailable:)
name:MPMovieNaturalSizeAvailableNotification
object:myMoviePlayer];
And in movieNaturalSizeAvailable:
, myVideoPlayer.naturalSize
gives you the desired value and after that, you can play the video.