ios - 从 AVAssetImageGenerator 生成图像在不同时间提供相同的图像副本

标签 ios avfoundation

我正在尝试使用以下代码从视频生成缩略图。它确实生成 UIImages 但图像在不同时间都是相同的。例如,对于持续 3 秒的视频,它会生成 6 张图像,但所有图像都是视频开头的相同图像。对我做错了什么有什么想法吗?

let asset = AVAsset(url: videoURL)
                let imageGenerator = AVAssetImageGenerator(asset: asset)

                let scale = 2
                let step = 1
                let duration = Int(CMTimeGetSeconds(asset.duration) * Double(scale))
                var epoches = [NSValue]()
                for i in stride(from: 1, to: duration, by: step) {
                    //let time = CMTimeMake(Int64(i), Int32(scale)) 
                    let time = CMTimeMakeWithSeconds(Double(i)/Double(scale), Int32(scale))
                    let cgImage = try! imageGenerator.copyCGImage(at: time, actualTime: nil)
                    let uiImage = UIImage(cgImage: cgImage)
                    self?.imagePool.append(uiImage)
                    epoches.append(NSValue(time: time))
                }

最佳答案

默认情况下,AVAssetImageGenerator 在为给定时间获取帧时给自己很大的容差。如果你使用 copyCGImageactualTime 你会在实践中看到它大约是一两秒,虽然技术上它是 kCMTimeFlags_PositiveInfinity,所以在你的短视频一半的帧将是重复的。

因此将公差设置为更小的值以查看独特的帧:

imageGenerator.requestedTimeToleranceBefore = CMTimeMake(1, 15)
imageGenerator.requestedTimeToleranceAfter = CMTimeMake(1, 15)

关于ios - 从 AVAssetImageGenerator 生成图像在不同时间提供相同的图像副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39525253/

相关文章:

ios - 用户界面图像 :imageNamed on ipad fails ok in simulator

ios - 如何创建自定义委托(delegate)方法,如 tableView cellForRowAtIndexPath 方法,它有 tableView 的争论?

ios - 无法弄清楚为什么 VideoDeviceInput 没有被添加到我的 AVCaptureSession

swift - 声音在模拟器中播放,但不在物理设备上播放

iphone - 通过 AVAssetReader 读取音频样本

swift - 尝试使用 AVFoundation AVAssetWriter 将 Metal 帧写入 Quicktime 文件时出现全黑帧

ios - 具有原始值的枚举,可编码

ios - 在 Swift 中从左到右循环 UISlider,反之亦然

ios - 快速将多个独立项目居中

objective-c - 为什么在预设为 640x480 时使用 AVFoundation 捕获图像会给我 480x640 图像?