仅测试了本机拍摄的mp4文件
- (void)setFileName:(NSString *)fileName{
_fileName = [fileName copy];
// 这里是获取本地沙盒的视频,远程url原理一样
// 记住如果是http地址记得用[NSURL URLWithString:urlStr]
// 若是本地视频地址要用[NSURL fileURLWithPath:path]
_videoUrl = [NSURL fileURLWithPath:[[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:VideoRecordsDirectory] stringByAppendingPathComponent:_fileName]];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:_videoUrl options:nil];
// 获取某一帧图片,这里获取第一帧
_videoImage = [self getthumImageForAsset:asset atTime:0];
}
// 获取视频某一帧的图片
- (UIImage *)getthumImageForAsset:(AVURLAsset *)asset atTime:(NSTimeInterval)time{
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
// 获取任意帧要设定这个,然后可根据传过来的参数time获取任意帧
// assetImageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
// assetImageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
CGImageRef thumImageRef = NULL;
// 获取哪一时间的帧图片
CFTimeInterval thumImageTime = time;
NSError *thumImageGenerationError = nil;
// 获取每秒多少帧
// float fps = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] nominalFrameRate];
// 重写CMTimeMake(a,b) a当前第几帧, b每秒钟多少帧.当前播放时间a/b CMTimeMakeWithSeconds(a,b) a当前时间,b每秒钟多少帧
// 这个时候即可获取第N帧图片
// thumImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(time, fps) actualTime:NULL error:&thumImageGenerationError];
thumImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumImageTime, 60) actualTime:NULL error:&thumImageGenerationError];
if (!thumImageRef)
NSLog(@"thumImageGenerationError %@", thumImageGenerationError);
UIImage *thumImage = thumImageRef ? [[UIImage alloc] initWithCGImage:thumImageRef] : nil;
return thumImage;
}
/** 获取视频的尺寸 */
+ (void)getVideoSizeWithURL:(NSURL *)URL complete:(void(^)(CGSize videoSize))complete{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:URL options:nil];
// 获取
// loadValuesAsynchronouslyForKeys是官方提供异步加载track的方法,防止线程阻塞
// 加载track是耗时操作
[asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:^{
// 一般视频都有至少两个track(轨道),根据track.mediaType判断track类型
// AVMediaTypeVideo表示视频轨道,AVMediaTypeAudio代表音频轨道,其他类型可以查看文档。
// 根据track的naturalSize属性即可获得视频尺寸
NSArray *array = asset.tracks;
CGSize videoSize = CGSizeZero;
for (AVAssetTrack *track in array) {
if ([track.mediaType isEqualToString:AVMediaTypeVideo]) {
// 注意修正naturalSize的宽高
videoSize = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);//CGSizeMake(track.naturalSize.height, track.naturalSize.width);
break;
}
}
if (asset.playable) {
dispatch_async(dispatch_get_main_queue(), ^{
!complete ? : complete(videoSize);
});
}
}];
}