视频首帧图

2022-08-18  本文已影响0人  简繁之间_来去自然

#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]]];
            }
        });
    });
}

上一篇下一篇

猜你喜欢

热点阅读