iOS拍摄多个屏幕截图
发布时间:2020-12-15 01:49:15 所属栏目:百科 来源:网络整理
导读:我有一个包含视频的NSURL,我想每秒录制一次该视频的帧数十次.我有代码可以捕获我的播放器的图像,但是我无法将其设置为每秒捕获10帧.我正在尝试这样的东西,但是它返回了视频的相同初始帧,正确的次数?这是我有的: AVAsset *asset = [AVAsset assetWithURL:vi
我有一个包含视频的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; } 但是,不是在视频的当前时间i获取帧,而是获得初始帧? 如何每秒10次获取视频帧? 谢谢您的帮助 :) 解决方法
您正在获取初始帧,因为您尝试使用浮点值创建CMTime:
CMTime time = CMTimeMake(i,10); 由于CMTimeMake函数将int64_t值作为第一个参数,因此您的float值将四舍五入为int,并且您将得到不正确的结果. 让我们稍微改变你的代码: 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |