iOS分解视频中所在帧

0x00 需求

把视频拆成图片,视频文件其实是一帧帧的图片,视频文件信息及结构这里就不再赘述了,网上有很多讲的都比较好的文章,请自行谷歌

0x01 代码实现(AVAssetImageGenerator)

/**
 *  把视频文件拆成图片保存在沙盒中
 *
 *  @param fileUrl        本地视频文件URL
 *  @param fps            拆分时按此帧率进行拆分
 *  @param completedBlock 所有帧被拆完成后回调
 */
- (void)splitVideo:(NSURL *)fileUrl fps:(float)fps completedBlock:(void(^)())completedBlock {
    if (!fileUrl) {
        return;
    }
    NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *avasset = [[AVURLAsset alloc] initWithURL:fileUrl options:optDict];
    
    CMTime cmtime = avasset.duration; //视频时间信息结构体
    Float64 durationSeconds = CMTimeGetSeconds(cmtime); //视频总秒数
    
    NSMutableArray *times = [NSMutableArray array];
    Float64 totalFrames = durationSeconds * fps; //获得视频总帧数
    CMTime timeFrame;
    for (int i = 1; i <= totalFrames; i++) {
        timeFrame = CMTimeMake(i, fps); //第i帧  帧率
        NSValue *timeValue = [NSValue valueWithCMTime:timeFrame];
        [times addObject:timeValue];
    }
    
    NSLog(@"------- start");
    AVAssetImageGenerator *imgGenerator = [[AVAssetImageGenerator alloc] initWithAsset:avasset];
    //防止时间出现偏差
    imgGenerator.requestedTimeToleranceBefore = kCMTimeZero;
    imgGenerator.requestedTimeToleranceAfter = kCMTimeZero;
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSInteger timesCount = [times count];
    [imgGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        printf("current-----: %lld\n", requestedTime.value);
        switch (result) {
            case AVAssetImageGeneratorCancelled:
                NSLog(@"Cancelled");
                break;
            case AVAssetImageGeneratorFailed:
                NSLog(@"Failed");
                break;
            case AVAssetImageGeneratorSucceeded: {
                NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%lld.png",requestedTime.value]];
                NSData *imgData = UIImagePNGRepresentation([UIImage imageWithCGImage:image]);
                [imgData writeToFile:filePath atomically:YES];
                if (requestedTime.value == timesCount) {
                    NSLog(@"completed");
                    if (completedBlock) {
                        completedBlock();
                    }
                }
            }
                break;
        }
    }];
}

0x10 获取单帧图片

- (nullable CGImageRef)copyCGImageAtTime:(CMTime)requestedTime actualTime:(nullable CMTime *)actualTime error:(NSError * __nullable * __nullable)outError CF_RETURNS_RETAINED;

requestedTime:要获取的帧时间CMTimeMake(a,b)

0x11 CMTime结构体

/*!
 @typedef CMTime
 @abstract Rational time value represented as int64/int32.
*/
typedef struct
{
 CMTimeValue value;  /*! @field value The value of the CMTime. value/timescale = seconds. */
 CMTimeScale timescale; /*! @field timescale The timescale of the CMTime. value/timescale = seconds.  */
 CMTimeFlags flags;  /*! @field flags The flags, eg. kCMTimeFlags_Valid, kCMTimeFlags_PositiveInfinity, etc. */
 CMTimeEpoch epoch;  /*! @field epoch Differentiates between equal timestamps that are actually different because
             of looping, multi-item sequencing, etc.  
             Will be used during comparison: greater epochs happen after lesser ones. 
             Additions/subtraction is only possible within a single epoch,
             however, since epoch length may be unknown/variable. */
} CMTime;

CMTime是专门用于表示视频时间的结构体
value不是指时间
timescale可以理解为帧率
获得秒数:value / timescale = seconds
创建CMTime 用 CMTimeMake(a, b) 当前第a帧,每秒b帧

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 写在前面 公司项目最近有个小视频功能,上传的视频最长只有15秒,所以需要实现一个视频剪辑的功能。发现微信有这个功能...
    FonkiOS阅读 7,819评论 8 24
  • 从视频中获取缩略图生成GIF图片,首先需要了解思路和要用到的开发框架,先来说一下思路: 1.在视频中按一定的时间,...
    辉的书阅读 2,067评论 0 0
  • 1.NSAssert NSAssert()是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递...
    字节码阅读 1,574评论 0 5
  • 教程一:视频截图(Tutorial 01: Making Screencaps) 首先我们需要了解视频文件的一些基...
    90后的思维阅读 4,821评论 0 3
  • 硬件编码相关知识(H264,H265) 阅读人群:研究硬件编码器应用于iOS开发中,从0研究关于硬件编解码,码流中...
    小东邪啊阅读 12,878评论 0 18