0

我正在尝试获取所有视频帧并将它们转换并存储为单独的图像。我在 AV Foundation Programming Guide 中使用此代码。

获取多个图像的代码是

CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 600);
CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 600);
CMTime end = CMTimeMakeWithSeconds(durationSeconds, 600);

这是硬编码的,但我想转换整个视频。我知道我可以使用 for 循环,但这durationsecond意味着我如何使用从乞求到结束来获取所有帧?

这是我的尝试

for(float f=0.0; f<=durationSeconds; f++) {
        [times addObject:[NSValue valueWithCMTime:CMTimeMakeWithSeconds(durationSeconds, 600)]];
}
4

1 回答 1

1

每当您要编写数百行几乎相同的代码时,都可能需要使用某种循环:

for (int currentFrame = 0; currentFrame < durationSeconds; ++currentFrame) {
    CMTime currentTime = CMTimeMakeWithSeconds(i, 600);
    // the rest of the code you need to create the image or whatever
}

该片段将每秒抓取一帧。如果你想每秒抓取 30 帧,它看起来更像这样:

const CGFloat framesPerSecond = 30.0;

for (int currentFrame = 0; currentFrame < (durationSeconds * framesPerSecond); ++currentFrame) {
    CMTime currentTime = CMTimeMakeWithSeconds(currentFrame/framesPerSecond, 600);
    // again, the code you need to create the image from this time
}

只需将值设置为framesPerSecond您想要捕获的每秒帧数即可。


作为免责声明,我对这些东西并不完全熟悉,因此 a<=可能适合此处的条件语句。


附录:我发布的代码只会获取要获取图像的时间戳。其余代码应如下所示:

AVAsset *myAsset = // your asset here
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset];

NSError *error;
CMTime actualTime;

CGImageRef currentImage = [imageGenerator copyCGImageAtTime:currentTime 
                                                 actualTime:&actualTime 
                                                      error:&error];

if (!error) {
    [someMutableArray addObject:[[UIImage alloc] initWithCGImage:currentImage]];
}
于 2014-07-06T02:31:22.277 回答