为什么AVAssetImageGenerator generateCGImagesAsynchronouslyForTimes崩溃应用程序

时间:2017-07-04 15:46:52

标签: ios avfoundation cgimageref avassetimagegenerator

我尝试使用generateCGImagesAsynchronouslyForTimes从视频中提取每秒2帧。但我的应用程序崩溃了。我正在监视内存使用情况,但它不会超过14 MB。

以下是代码:

- (void) createImagesFromVideoURL:(NSURL *) videoUrl atFPS: (int) reqiuredFPS completionBlock: (void(^) (NSMutableArray *frames, CGSize frameSize)) block
{
    NSMutableArray *requiredFrames = [[NSMutableArray alloc] init];

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];

    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];

    generator.requestedTimeToleranceAfter =  kCMTimeZero;

    generator.requestedTimeToleranceBefore =  kCMTimeZero;

    generator.appliesPreferredTrackTransform = YES;

    UIImage *sampleGeneratedImage;

    for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) *  reqiuredFPS ; i++)
    {
        CMTime time = CMTimeMake(i, reqiuredFPS);

        NSError *err;

        CMTime actualTime;

        CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err];

        if (! err)
        {
            sampleGeneratedImage = [[UIImage alloc] initWithCGImage:image];
            break;
        }
    }

    //Get the maximum size from 1 frame
    generator.maximumSize = [self getMultipleOf16AspectRatioForCurrentFrameSize:sampleGeneratedImage.size];

    NSMutableArray *requestedFrameTimes = [[NSMutableArray alloc] init];

    for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) *  reqiuredFPS ; i++)
    {
        CMTime time = CMTimeMake(i, reqiuredFPS);

        [requestedFrameTimes addObject:[NSValue valueWithCMTime:time]];
    }

    [generator generateCGImagesAsynchronouslyForTimes:[requestedFrameTimes copy] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {

        if (image)
        {
            UIImage *generatedImage = [UIImage imageWithCGImage:image];

            [requiredFrames addObject:generatedImage];
        }

        if (CMTimeCompare(requestedTime, [[requestedFrameTimes lastObject] CMTimeValue]) == 0)
        {
            NSLog(@"Image processing complete");

            dispatch_async(dispatch_get_main_queue(), ^{
                block(requiredFrames, generator.maximumSize);
            });
        }

        else
        {
            NSLog(@"Getting frame at %lld", actualTime.value/actualTime.timescale);
        }
    }];
}

0 个答案:

没有答案