Anson Yao Anson Yao - 1 year ago 187
iOS Question

Generate images from AVAssetImageGenerator

I am trying to generate thumbnail images from a video using the following code. It does generate UIImages but the images are all the same at different time. For example, for a video which lasts 3 seconds, it will generate 6 images but all the images are the same image for the very beginning of the video. Any ideas on what I did wrong?

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)
epoches.append(NSValue(time: time))

Answer Source

By default AVAssetImageGenerator gives itself very generous tolerances when fetching frames for a given time. If use use copyCGImage's actualTime you'll see in practice that it's something like one or two seconds, although technically it's kCMTimeFlags_PositiveInfinity, so in your short video half of your frames will be duplicates.

So set the tolerances to something smaller to see unique frames:

imageGenerator.requestedTimeToleranceBefore = CMTimeMake(1, 15)
imageGenerator.requestedTimeToleranceAfter = CMTimeMake(1, 15)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download