Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate images from AVAssetImageGenerator gives same image duplicates for different times

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)
                    self?.imagePool.append(uiImage)
                    epoches.append(NSValue(time: time))
                }
like image 239
Anson Yao Avatar asked Jan 06 '23 08:01

Anson Yao


1 Answers

By default AVAssetImageGenerator gives itself very generous tolerances when fetching frames for a given time. If you 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)
like image 68
Rhythmic Fistman Avatar answered Feb 11 '23 09:02

Rhythmic Fistman