ios - 获取视频 IOS 6 的所有帧

标签 ios objective-c avfoundation frame-rate image-generation

我想将 iOS6 中视频的所有帧放入 NSArray。 我使用这段代码:

-(void) getAllImagesFromVideo
{
   imagesArray = [[NSMutableArray alloc] init];
   times = [[NSMutableArray alloc] init];

   for (Float64 i = 0; i < 15; i += 0.033) // For 25 fps in 15 sec of Video
   {
       CMTime time = CMTimeMakeWithSeconds(i, 60);
      [times addObject:[NSValue valueWithCMTime:time]];
   } 

   [imageGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {

      if (result == AVAssetImageGeneratorSucceeded)
      {
         UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image];

         [imagesArray addObject:generatedImage];
     }
   }];
}

在 iPad 模拟器上,延迟为 90~100 秒,在 iPad 设备上,收到内存警告并最终崩溃。

任何想法,解决方案?使用另一个更低级别的框架/库? C++? 对我来说很重要!帮我! :)

谢谢!!!

最佳答案

你需要:

  1. 像@zimmryan 提到的那样使用 CGImageRelease
  2. 在循环中使用@autoreleasepool block
  3. 不要将图像存储在内存中,将它们存储在您的文档目录中

我是这样做的:(注意我使用同步版本来提取图像,如果你选择异步版本应该没关系)

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.requestedTimeToleranceAfter =  kCMTimeZero;
generator.requestedTimeToleranceBefore =  kCMTimeZero;
for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) *  FPS ; i++){
  @autoreleasepool {
    CMTime time = CMTimeMake(i, FPS);
    NSError *err;
    CMTime actualTime;
    CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err];
    UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image];
    [self saveImage: generatedImage atTime:actualTime]; // Saves the image on document directory and not memory
    CGImageRelease(image);
  }
}

编辑:

在创建大量临时对象时,您应该始终考虑使用@autoreleasepool(参见 https://developer.apple.com/library/mac/documentation/cocoa/conceptual/memorymgmt/articles/mmAutoreleasePools.html)

关于ios - 获取视频 IOS 6 的所有帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436552/

相关文章:

ios - 用自己的initWithFrame初始化一个类可以吗?

iphone - objective-c int 进行双重计算

iphone - 使用 iPhone 的 ffmpeg 库旋转视频

objective-c - 从代码中显示两个 NSTableView 项目的最简单的方法?

objective-c - 替换 objective-c 中的转义字符序列

ios - Swift IOS 使用 AVFoundation 录制视频和音频

iphone - 在 iOS 中将 h263 转换为 h264

ios - 如果用户在返回键盘之前按下按钮,如何将按钮的操作应用于文本字段

iphone - 将 ZXing 连接到 xcode 中的按钮

ios - 当我单击 Objective C 中的按钮时,为什么未从 tableViewCell 获取文本字段数据?