AVAssetImageGenerator复制图像失败 [英] AVAssetImageGenerator fails at copying image
问题描述
我正在使用AVAssetImageGenerator
从视频的最后一帧创建图像.这通常可以正常工作,但copyCGImageAtTime
有时会因错误
I am using AVAssetImageGenerator
to create an image from the last frame of a video. This usually works fine, but every now and then copyCGImageAtTime
fails with the error
NSLocalizedDescription = "Cannot Open";
NSLocalizedFailureReason = "This media cannot be used.";
NSUnderlyingError = "Error Domain=NSOSStatusErrorDomain Code=-12431";
我正在验证AVAsset不是零,并且我是直接从资产中拉出CMTime,所以我不明白为什么这种情况一直在发生.仅当尝试获取最后一帧时才会发生这种情况,如果我改用kCMTimeZero
,它似乎可以工作.
I am verifying that the AVAsset is not nil and I'm pulling the CMTime directly from the asset, so I do not understand why this keeps happening. This only happens when trying to get the last frame, if I use kCMTimeZero
instead, it seems to work.
- (void)getLastFrameFromAsset:(AVAsset *)asset completionHandler:(void (^)(UIImage *image))completion
{
NSAssert(asset, @"Tried to generate last frame from nil asset");
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.requestedTimeToleranceBefore = kCMTimeZero;
gen.requestedTimeToleranceAfter = kCMTimeZero;
gen.appliesPreferredTrackTransform = YES;
CMTime time = [asset duration];
NSError *error = nil;
CMTime actualTime;
CGImageRef imageRef = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
NSAssert(image, @"Failed at generating image from asset's last frame");
completion(image);
CGImageRelease(imageRef);
}
这似乎相关,但并没有解决我的问题.
This seems to be related, but it did not solve my problem.
推荐答案
没有任何办法可以保证资产的 video 轨道位于[asset duration]
.它的持续时间可以短于整个资产.由于您将公差设置为kCMTimeZero
,因此唯一可能的解决方法就是失败.
Nothing guarantees that your asset's video track exists at [asset duration]
. It's duration can be shorter than the whole asset. Since you set the tolerance to kCMTimeZero
the only possible resolution is failure.
编辑:为澄清起见,当资产的音频轨道比视频轨道稍长时,就会出现此问题.
To clarify, the issue emerges when you have an asset with audio track slightly longer than the video track.
这篇关于AVAssetImageGenerator复制图像失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!