/**

 *  把视频文件拆成图片保存在沙盒中

 *

 *  @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];

    }

    

    AVAssetImageGenerator *imgGenerator = [[AVAssetImageGenerator alloc] initWithAsset:avasset];

    //防止时间出现偏差

    imgGenerator.requestedTimeToleranceBefore = kCMTimeZero;

    imgGenerator.requestedTimeToleranceAfter = kCMTimeZero;

    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: {

                if (requestedTime.value == timesCount) {

                    NSLog(@"completed");

                    if (completedBlock) {                        completedBlock();

                    }

                }

            }

                break;

        }

    }];

}