Derek Saunders
Derek Saunders

Reputation: 411

Can't seem to get video height for AVPlayerLayer

I can't seem to get the height of the video from the URL I have. Every time I log the playerLayer.videoRect.bounds.size.the height returns 0.000. Any help would be appreciated on how to adjust the playerLayer's height based on the video.

I have the playerLayer's height set to half the height of the view just to get the video to show up.

Here is my edited code:

NSURL *videoURL = [NSURL URLWithString:self.videoURL];
self.player = [AVPlayer playerWithURL:videoURL];

AVAssetTrack* track = [[AVAsset assetWithURL:videoURL] tracksWithMediaType:AVMediaTypeVideo].firstObject;
CGSize size = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);
CGFloat videoWidth = size.width;
CGFloat videoHeight = size.height;

NSLog(@"%f wide, %f high)", videoWidth, videoHeight);

self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = CGRectMake(0, self.navigationController.navigationBar.bottom, self.view.bounds.size.width, videoHeight);
[self.view.layer addSublayer:self.playerLayer];
[self.player play];
self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

Upvotes: 0

Views: 251

Answers (2)

Luan Tran
Luan Tran

Reputation: 1142

You can use AvAssetTrack to get size of video.

NSString* urlString = @"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
NSURL* url = [[NSURL alloc]initWithString:urlString];

AVAssetTrack* track = [[AVAsset assetWithURL:url] tracksWithMediaType:AVMediaTypeVideo].firstObject;
CGSize size = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);
CGFloat width = size.width;  // 640
CGFloat height = size.height; // 360

Note: You should put it in background mode because it will block main thread until finish get size success.

Upvotes: 1

matt
matt

Reputation: 535556

There are two problems:

  • You are asking for this information too soon. Like everything else about video, gathering the video's size takes time.

  • You have the dependency order backwards. The videoRect depends upon the layer's bounds. But you have not given it any bounds; it has zero size.

Upvotes: 0

Related Questions