iOS拍摄多个屏幕截图

iqu*_*rio 8 video xcode camera ios

我有一个包含视频的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;
}
Run Code Online (Sandbox Code Playgroud)

但是,不是在视频的当前时间i获取帧,我只是得到初始帧?

如何每秒10次获取视频帧?

谢谢您的帮助 :)

Vla*_*r K 14

您正在获取初始帧,因为您尝试使用浮点值创建CMTime:

CMTime time = CMTimeMake(i, 10);
Run Code Online (Sandbox Code Playgroud)

由于CMTimeMake函数将int64_t值作为第一个参数,因此您的float值将舍入为int,并且您将得到不正确的结果.

让我们稍微改变你的代码:

1)首先,您需要查找需要从视频中获取的总帧数.你写道,你需要每秒10帧,所以代码将是:

int requiredFramesCount = seconds * 10;
Run Code Online (Sandbox Code Playgroud)

2)接下来,您需要找到一个值,该值将增加每一步的CMTime值:

int64_t step = vidLength.value / requiredFramesCount;
Run Code Online (Sandbox Code Playgroud)

3)最后,您需要将requestedTimeToleranceBefore和requestedTimeToleranceAfter设置为kCMTimeZero,以便在精确时间获取帧:

imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
Run Code Online (Sandbox Code Playgroud)

以下是您的代码的外观:

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;
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*lad 2

您存储CMTimeMake(A, B)一个有理数、一个精确的分数 A / B 秒,并且该函数的第一个参数采用 int 值。对于 20 秒的视频,您将在周期的最后一次迭代中捕获一个时间为 ((int) 19.9) / 10 = 1.9 秒的帧。使用CMTimeMakeWithSeconds(i, NSEC_PER_SEC)函数来解决这个时间问题。