AVPlayer获取视频尺寸
AVPlayer是苹果官方提供的视频处理类,有非常强的定制性,实际开发中我们需要获取视频的相关信息用于定制相关UI,废话不多说直接上代码:
NSString *path = @"http://....*.mp4";
NSURL *url = [NSURL URLWithString:path];
// NSURL *url = [[NSBundle mainBundle] URLForResource:@"m" withExtension:@"mp4"];
// NSURL *url = [NSURL fileURLWithPath:@"/Users/xiexiaolong1/Desktop/m.mp4"];
AVAsset *asset = [AVAsset assetWithURL:videoURl];
self.asset = asset;
记住如果是http地址记得用[NSURL URLWithString:path],若是本地视频地址要用[NSURL fileURLWithPath:path]
[asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (asset.playable) {
[self loadedResourceForPlay];
}
});
}];
loadValuesAsynchronouslyForKeys方法是官方提供异步加载track的方法,防止线程阻塞(加载track是耗时操作)
- (void)loadedResourceForPlay{
NSArray *array = self.asset.tracks;
CGSize videoSize = CGSizeZero;
for (AVAssetTrack *track in array) {
if ([track.mediaType isEqualToString:AVMediaTypeVideo]) {
videoSize = track.naturalSize;
}
}
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:self.asset];
AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:player];
CGFloat videoWidth = 200;
layer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
[self.layer addSublayer:layer];
[player play];
}
一般视频都有至少两个track(笔者不知道如何翻译),根据track.mediaType判断track类型,AVMediaTypeVideo表示不带声音的视频,AVMediaTypeAudio代表音频,其他类型可以查看文档。根据track的naturalSize属性即可获得视频尺寸,根据尺寸的比例设置AVPlayerLayer尺寸,防止黑边,达到满屏效果。
layer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);这行这句话之前最好用Block回调设置layer的父视图的尺寸.
demo地址:https://github.com/mgfjxxiexiaolong/CoreAnimation.git
当前文件夹下,在终端执行
git checkout AVPlayerLayer
git checkout c962ca502449e7707fbabe84909a40405d4b4e0a
即可
有疑问可加我QQ共同学习