Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var data : [CustomData] = []
var generator: AVAssetImageGenerator!
var numberOfFrames = 12
var frames:[UIImage] = []{
didSet{
DispatchQueue.main.async {
self.setCustomData()
}
}
}
func imagesFromVideo(url: URL) {
let asset = AVURLAsset(url: url)
generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
generator.apertureMode = .encodedPixels
let duration:Float64 = CMTimeGetSeconds(asset.duration)
let frameInterval = duration/Double(numberOfFrames)
var nsValues : [NSValue] = []
for index in stride(from: 0, through: duration, by: frameInterval) {
let cmTime = CMTime(seconds: Double(index), preferredTimescale: 60)
let nsValue = NSValue(time: cmTime)
nsValues.append(nsValue)
}
self.getFrame(nsValues: nsValues)
}
private func getFrame(nsValues:[NSValue]) {
var images : [UIImage] = []
generator.generateCGImagesAsynchronously(forTimes: nsValues) { (time, cgImage, time2, result, error) in
if let cgImage = cgImage{
images.append(UIImage(cgImage: cgImage))
}
if images.count == nsValues.count{
self.frames = images
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment