Exporting image sequence from video in swift

293 views Asked by At

I have the below code to export a video (60fps) to an image sequence. However, despite loads of stackoverflow examples, I seem to not master properly the CMTime, as images 1-30 are the same, then 31-90 are the same, then 91-130, 131-150... like if the generated sequence would be stop motion.

var seq=0
let duration:Float64 = CMTimeGetSeconds(asset.duration)
let fps = tracks.first!.nominalFrameRate

for index:Float64 in stride(from: 0, to: duration, by: Double(1/fps)) {
    let time:CMTime = CMTimeMakeWithSeconds(index, preferredTimescale:Int32(NSEC_PER_SEC))
    var image:CGImage
    do {
        try image = generator.copyCGImage(at:time, actualTime:nil)
        let bitmapRep = NSBitmapImageRep(cgImage: image)
        let data = bitmapRep.representation(using: .jpeg, properties: [:])
        let oneimagepath=newpath.appendingPathComponent("Sequence.\(String(format: "%04d", seq)).jpg")
        seq = seq+1
        try data?.write(to: oneimagepath, options: .atomicWrite)
    } catch {
        print(error.localizedDescription)
    }
}

Is the issue into my CMTime, or somewhere else ? It's like if it would convert my decimal time to an int.

0

There are 0 answers