I want last frame of video and my code is shown below:
let asset : AVURLAsset = AVURLAsset(URL: videoURL, options: nil)
let generate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
generate.appliesPreferredTrackTransform = true
var err : NSError? = nil
var lastFrameTime = Int64(CMTimeGetSeconds(asset.duration))
let time : CMTime = CMTimeMake(lastFrameTime, 30)
let imgRef : CGImageRef = generate.copyCGImageAtTime(time, actualTime: nil, error: &err)
let img : UIImage = UIImage(CGImage: imgRef)!
But I am not getting last frame , I am getting first frame, provide me solution for this.
I used Pooja's code as a starting point but it doesn't get the last frame. it gets something close to the last frame. Here is my solution for getting the actual last frame. If frame accuracy is important, then you have to use:
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
Be aware that it may take longer to generate this frame accurate last frame so you probably want to do it on a background thread.
Here is the code I am using:
let imageGenerator = AVAssetImageGenerator(asset: asset!)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
let composition = AVVideoComposition(propertiesOfAsset: asset!)
let time = CMTimeMakeWithSeconds(asset!.duration.seconds, composition.frameDuration.timescale)
do {
let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
}
catch let error as NSError {
print("Image generation failed with error \(error)")
}
Hope this helps.
You can get last frame of video in Objective-C as mentioned below:-
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVAssetImageGenerator *generate = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *error;
int64_t lastFrameTime = CMTimeGetSeconds(asset.duration)*60.0;
CMTime time = CMTimeMake(lastFrameTime, 2);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:nil error:&error];
UIImage *image = [UIImage imageWithCGImage:imgRef];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With