0

我正在尝试将视频转换为一系列图像帧并将它们保存到文件中。然而,大约 5 帧后,我收到了内存警告,并且应用程序由于内存压力很快退出。图像大小约为 10kb。我的代码在下面,我做错了什么?

在此先感谢,本。

-(void)framesFromVideo:(AVURLAsset *)asset{
    NSArray *times = [self timeSequenceFromAsset:asset];

    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folderPath = rootPath;

    __block int i=0;
    generator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    generator.apertureMode = AVAssetImageGeneratorApertureModeCleanAperture;
    generator.appliesPreferredTrackTransform = TRUE;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    [generator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){

        if (result == AVAssetImageGeneratorSucceeded) {
            NSString *imgPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];
            [self writeImageRef:im toPath:imgPath];
        }else if (result == AVAssetImageGeneratorFailed){
            NSLog(@"Frame generation failed with error:%@", error);
        }else if (result == AVAssetReaderStatusCancelled){
            NSLog(@"Frame generation cancelled");
        }
        NSLog(@"Completed frame");
        i++;
    }];
}
4

1 回答 1

0

我在类似的实现中遇到了这个问题,但我没有使用完成块。为了解决我的“内存压力”,我不得不释放 CGImageRef。

尝试添加...

CFRelease(im);

所以 ...

-(void)framesFromVideo:(AVURLAsset *)asset{
    NSArray *times = [self timeSequenceFromAsset:asset];

    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folderPath = rootPath;

    __block int i=0;
    generator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    generator.apertureMode = AVAssetImageGeneratorApertureModeCleanAperture;
    generator.appliesPreferredTrackTransform = TRUE;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    [generator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){

        if (result == AVAssetImageGeneratorSucceeded) {
            NSString *imgPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];
            [self writeImageRef:im toPath:imgPath];
            CFRelease(im);
        }else if (result == AVAssetImageGeneratorFailed){
            NSLog(@"Frame generation failed with error:%@", error);
        }else if (result == AVAssetReaderStatusCancelled){
            NSLog(@"Frame generation cancelled");
        }
        NSLog(@"Completed frame");
        i++;
    }];
}
于 2014-04-27T00:06:28.977 回答