iOS AVAssetImageGenerator从视频中截取图片 AVAsynchronousKeyValueLoading

来源:互联网 发布:dota2无法连接网络 编辑:程序博客网 时间:2024/05/21 10:11

准备使用Asset

初始化一个asset(或者track)并不是表示asset里面所有的信息都是马上可用的。它需要一些时间去计算,即使是durtation(比如没有摘要信息的mp3文件),你应该使用AVAsynchronousKeyValueLoading协议获取这些值,通过- loadValuesAsynchronouslyForKeys:completionHandler:在handler里面获取你要的值。你可以用statusOfValueForKey:error:测试一个属性的value是否成功获取,当一个assert第一次被加载,大多数属性的值是AVKeyValueStatusUnknown状态,为了获取一个或多个属性的值,你要调用loadValuesAsynchronouslyForKeys:completionHandler:,在comletiton handler里面,你可以根据属性的状态做任何合适的处理。你要处理加载没有成功的情况,可能因为一些原因比如网络不可连接,又或者loading被取消。

NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];NSArray *keys = @[@"duration"];[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {    NSError *error = nil;    AVKeyValueStatus tracksStatus = [asset statusOfValueForKey:@"duration" error:&error];        switch (tracksStatus) {            case AVKeyValueStatusUnknown:                break;            case AVKeyValueStatusLoading:                break;            case AVKeyValueStatusLoaded://                [self updateUserInterfaceForDuration];                break;            case AVKeyValueStatusFailed:                break;            case AVKeyValueStatusCancelled:                // Do whatever is appropriate for cancelation.                break;        }}];

如果你想要播放asset,你应该加载他的tracks属性。

从video中获取静态图片

从asset中获取静态图片(比如说缩略图),你可以用AVAssetImageGenerator对象。可以用asset初始化一个AVAssetImageGenerator对象.即使asset在初始化的时候没有可见的track也能成功,所以你应该检测asset是否有track,使用tracksWithMediaCharacteristic:

AVAsset anAsset = <#Get an asset#>;if ([[anAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0) {    AVAssetImageGenerator *imageGenerator =        [AVAssetImageGenerator assetImageGeneratorWithAsset:anAsset];    // Implementation continues...}

你还可以设置imagegenerator的其他属性,比如,你可以指定生成图片的最大的分辨率,你可以生成指定时间的一张图片,或者一系列图片。你必须一直持有generator的引用,直到生成所有的图片。

生成单个图片

你可以使用copyCGImageAtTime:actualTime:error:生成一张指定时间点的图片。AVFoundation不一定能精确的生成一张你所指定时间的图片,所以你可以在第二个参数传一个CMTime的指针,用来获取所生成图片的精确时间。

AVAsset *myAsset = <#An asset#>];AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset];Float64 durationSeconds = CMTimeGetSeconds([myAsset duration]);CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);NSError *error;CMTime actualTime;CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];if (halfWayImage != NULL) {    NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));    NSString *requestedTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, midpoint));    NSLog(@"Got halfWayImage: Asked for %@, got %@", requestedTimeString, actualTimeString);    UIImage *image = [UIImage imageWithCGImage:halfWayImage];        // Do something interesting with the image.    CGImageRelease(halfWayImage);}

生成一系列图片

为了生成一系列图片,你可以调用generateCGImagesAsynchronouslyForTimes:completionHandler:,第一个参数是一个包含NSValue类型的数组,数组里每一个对象都是CMTime结构体,表示你想要生成的图片在视频中的时间点,第二个参数是一个block,每生成一张图片都会回调这个block,这个block提供一个result的参数告诉你图片是否成功生成或者图片生成操作是否取消。

在你的block实现中,需要检查result,判断image是否成功生成,另外,确保你持有image generator直到生成图片的操作结束。

AVAsset *myAsset = <#An asset#>];// Assume: @property (strong) AVAssetImageGenerator *imageGenerator;self.imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:myAsset];Float64 durationSeconds = CMTimeGetSeconds([myAsset duration]);CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 600);CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 600);CMTime end = CMTimeMakeWithSeconds(durationSeconds, 600);NSArray *times = @[NSValue valueWithCMTime:kCMTimeZero],                  [NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird],                  [NSValue valueWithCMTime:end]];[imageGenerator generateCGImagesAsynchronouslyForTimes:times                completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime,                                    AVAssetImageGeneratorResult result, NSError *error) {                NSString *requestedTimeString = (NSString *)                    CFBridgingRelease(CMTimeCopyDescription(NULL, requestedTime));                NSString *actualTimeString = (NSString *)                    CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));                NSLog(@"Requested: %@; actual %@", requestedTimeString, actualTimeString);                if (result == AVAssetImageGeneratorSucceeded) {                    // Do something interesting with the image.                }                if (result == AVAssetImageGeneratorFailed) {                    NSLog(@"Failed with error: %@", [error localizedDescription]);                }                if (result == AVAssetImageGeneratorCancelled) {                    NSLog(@"Canceled");                }  }];

你也可以取消生成图片的操作,通过想generator发送cancelAllCGImageGeneration的消息。

原创粉丝点击