我有一个包含视频的 NSURL ,我想每秒十次录制该视频的一帧。我有代码可以捕获我的播放器的图像,但是我无法将其设置为每秒捕获10帧。我正在尝试这样的东西,但是它返回了视频的相同初始帧,正确的次数?这就是我所拥有的:
AVAsset *asset = [AVAsset assetWithURL:videoUrl];
CMTime vidLength = asset.duration;
float seconds = CMTimeGetSeconds(vidLength);
int frameCount = 0;
for (float i = 0; i < seconds;) {
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(i, 10);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
NSString* filename = [NSString stringWithFormat:@"Documents/frame_%d.png", frameCount];
NSString* pngPath = [NSHomeDirectory() stringByAppendingPathComponent:filename];
[UIImagePNGRepresentation(thumbnail) writeToFile: pngPath atomically: YES];
frameCount++;
i = i + 0.1;
}
但是我没有在视频的当前时间获取帧,而是获得初始帧?
如何每秒10次获取视频帧?
感谢您的帮助:)
答案 0 :(得分:13)
您正在获取初始帧,因为您尝试使用浮点值创建CMTime:
CMTime time = CMTimeMake(i, 10);
由于 CMTimeMake 函数将 int64_t 值作为第一个参数,因此您的浮点值将四舍五入为整数,并且您将得到不正确的结果。
让我们稍微改变你的代码:
1)首先,您需要查找需要从视频中获取的总帧数。你写道,你需要每秒10帧,所以代码将是:
int requiredFramesCount = seconds * 10;
2)接下来,您需要找到一个值,该值将在每一步增加您的CMTime值:
int64_t step = vidLength.value / requiredFramesCount;
3)最后,您需要将requestedTimeToleranceBefore和requestedTimeToleranceAfter设置为kCMTimeZero,以便在精确时间获取帧:
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
以下是您的代码的样子:
CMTime vidLength = asset.duration;
float seconds = CMTimeGetSeconds(vidLength);
int requiredFramesCount = seconds * 10;
int64_t step = vidLength.value / requiredFramesCount;
int value = 0;
for (int i = 0; i < requiredFramesCount; i++) {
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
CMTime time = CMTimeMake(value, vidLength.timescale);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
NSString* filename = [NSString stringWithFormat:@"Documents/frame_%d.png", i];
NSString* pngPath = [NSHomeDirectory() stringByAppendingPathComponent:filename];
[UIImagePNGRepresentation(thumbnail) writeToFile: pngPath atomically: YES];
value += step;
}
答案 1 :(得分:2)
使用CMTimeMake(A, B)
存储有理数,精确分数A / B秒,此函数的第一个参数采用int值。对于20秒的视频,您将在循环的最后一次迭代中捕获具有时间((int)19.9)/ 10 = 1.9秒的帧。使用CMTimeMakeWithSeconds(i, NSEC_PER_SEC)
功能解决此时间问题。