Generate images from AVAssetImageGenerator gives same image duplicates for different times

≡放荡痞女 提交于 2020-03-22 07:43:29

问题


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))
                }

回答1:


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)


来源:https://stackoverflow.com/questions/39525253/generate-images-from-avassetimagegenerator-gives-same-image-duplicates-for-diffe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!