我尝试过同步执行此操作:
AVURLAsset *as = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *ima = [[AVAssetImageGenerator alloc] initWithAsset:as];
NSError *err = NULL;
CMTime time = CMTimeMake(0, 30);
CGImageRef imgRef = [ima copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *currentImg = [[UIImage alloc] initWithCGImage:imgRef];
callback(currentImg, err);
并且异步:
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef imgRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(@"couldn't generate thumbnail, error:%@", error);
callback(nil, error);
}
UIImage *thumbnail = [UIImage imageWithCGImage:imgRef];
callback(thumbnail, nil);
};
CGSize maxSize = CGSizeMake(128, 128);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
无论哪种方式,我都会得到AVFoundationErrorDomain Code=-11800
-NSLocalizedFailureReason=An unknown error occurred
和一个零图像。
知道我做错了什么吗?
编辑
这是我刚刚尝试过的第三个选项,但产生的错误相同:
NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @NO };
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:options];
NSArray *keys = [NSArray arrayWithObject:@"readable"];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *err = NULL;
CMTime time = CMTimeMake(1, 30);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *thumbnail = [UIImage imageWithCGImage:imgRef];
dispatch_async(dispatch_get_main_queue(), ^{
callback(thumbnail, err);
});
}];