从AVAssetImageGenerator生成图像可在不同时间提供相同的图像副本 [英] Generate images from AVAssetImageGenerator gives same image duplicates for different times

查看:95
本文介绍了从AVAssetImageGenerator生成图像可在不同时间提供相同的图像副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

默认情况下,AVAssetImageGenerator在获取给定时间的帧时具有非常大的容差.如果使用copyCGImageactualTime,您会在实践中看到大约一秒钟或两秒钟,尽管从技术上讲,它是kCMTimeFlags_PositiveInfinity,所以在您的短视频中,一半帧是重复的.

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)

这篇关于从AVAssetImageGenerator生成图像可在不同时间提供相同的图像副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆