#import <SDWebImage/UIImageView+WebCache.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
/// 展示视频地址首帧图
/// @param videoUrl 视频地址
/// @param imgUrl 图片地址, 视频地址获取首帧失败时使用
/// @param imgV 展示首帧的ImageView
- (void)setVideoFirstFrame:(NSString *)videoUrl imgUrl:(NSString *)imgUrl img:(UIImageView *)imgV {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL * url = [NSURL URLWithString:videoUrl];
AVURLAsset * asset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator * generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = true;
generator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef imgRef = NULL;
NSError * error = nil;
// CMTimeMake(设置的第几帧, 帧率)
imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 60) actualTime:NULL error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
if (imgRef) {
imgV.image = [[UIImage alloc] initWithCGImage:imgRef];
}else{
[imgV sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageWithColor:[UIColor lightGrayColor]]];
}
});
});
}
网友评论