简体   繁体   中英

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;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM