由于是通过AVAsset来处理的,所以我们要导入
#import <AVFoundation/AVFoundation.h>
/// 根据视频url对指定时间的视频截图
/// @param videoUrlStr 视频url
/// @param seconds 时间 如果是封面图传0,即取0秒的视频位置
+ (void)getVideoThumbImageWithUrlStr:(NSString *)videoUrlStr seconds:(NSTimeInterval)seconds handle:(void(^)(UIImage *thumbImage,NSError *error))handle;
/// 根据视频url对指定时间的视频截图
+ (void)getVideoThumbImageWithUrlStr:(NSString *)videoUrlStr seconds:(NSTimeInterval)seconds handle:(void(^)(UIImage *thumbImage,NSError *error))handle{
//由于是获取线上的视频封面图,这里需要异步处理,防止阻塞主线程
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//根据url创建asset
AVURLAsset *asset = [[AVURLAsset alloc]initWithURL:[NSURL URLWithString:videoUrlStr] options:nil];
//创建集合的轨道
AVAssetTrack *track = [asset tracksWithMediaType:AVMediaTypeVideo].firstObject;
//创建AVAssetImageGenerator
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
//设置最大尺寸
generator.maximumSize = track.naturalSize;
CMTime actualTime;
NSError *error = nil;
CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMakeWithSeconds(seconds, asset.duration.timescale) actualTime:&actualTime error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
if (imageRef) {
UIImage *thumbImage = [[UIImage alloc]initWithCGImage:imageRef];
handle(thumbImage,error);
} else {
NSLog(@"截图失败==%@",error.domain.description);
handle(nil,error);
}
});
});
}
网友评论