使用Av基础提取视频帧

时间:2013-11-01 14:25:40

标签: ios objective-c video avfoundation cgimageref

我使用此方法生成视频的帧

-(NSMutableArray *)generateThumbnailsFromUrl:(NSURL *)videoURl{

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

Float64 durationFrames = CMTimeGetSeconds([asset duration]) * 30.0;

AVMutableComposition *myComp = [AVMutableComposition composition];

AVMutableCompositionTrack *compositionVideoTrack = [myComp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

NSError *error = nil;
BOOL ok = NO;
CGImageRef imgRef;
UIImage *currentImg;
CMTime time,startTime,endTime;
CMTimeRange myRange;
AVAssetTrack *sourceVideoTrack;

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

AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:myComp];
@try {

for (int i = 0; i < floor(durationFrames); i++) {

    startTime = CMTimeMake(i, 30);
    endTime = CMTimeMake(i+1, 30);

    myRange = CMTimeRangeMake(startTime, endTime);

    sourceVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];

    ok = [compositionVideoTrack insertTimeRange:myRange ofTrack:sourceVideoTrack atTime:kCMTimeZero error:&error];

    if (!ok) {
        // Deal with the error.
        NSLog(@"error %@ on %d",error,i);
    }else{
    time = CMTimeMake(0,1);

    imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&error];
    if(imgRef != nil)
    {
     currentImg = [[UIImage alloc] initWithCGImage:imgRef];

    if(currentImg!=nil)
        [frameArray addObject:currentImg];
    }
}
        currentImg=nil;
        CGImageRelease(imgRef);
        ok=NO;
    }
}
    @catch (NSException *exception) {
        NSLog(@"exption is %@",exception);
    }
return frameArray;}

但我在这一行中遇到了严重的问题imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&error];

有时在执行过程中冻结此处,无异常,结果且无需继续执行! 有谁可以帮我或向我解释这个问题?

是否有办法检查命令的执行是否更具特定时间并杀死该命令?

1 个答案:

答案 0 :(得分:0)

根据this解决方案

你可以

[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];
     }
   }];