How to implement AVAssetImageGenerator.copyCGImageAtTime in fast

So far I have the following

let assetUrl = NSURL.URLWithString(self.targetVideoString) let asset: AVAsset = AVAsset.assetWithURL(assetUrl) as AVAsset let imageGenerator = AVAssetImageGenerator(asset: asset); let time : CMTime = CMTimeMakeWithSeconds(1.0, 1) let actualTime : CMTime let myImage: CGImage =imageGenerator.copyCGImageAtTime(requestedTime: time, actualTime:actualTime, error: <#NSErrorPointer#>) 

The last line is where I get lost ... I just want to capture the image in 1.0 second

+6
source share
4 answers

Function is declared as

 func copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer<CMTime>, error outError: NSErrorPointer) -> CGImage! 

and you have to pass (initialized) CMTime and NSError? variables as "in-out expression" with & :

 let assetUrl = NSURL(string: ...) let asset: AVAsset = AVAsset.assetWithURL(assetUrl) as AVAsset let imageGenerator = AVAssetImageGenerator(asset: asset); let time = CMTimeMakeWithSeconds(1.0, 1) var actualTime : CMTime = CMTimeMake(0, 0) var error : NSError? let myImage = imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime, error: &error) 

Please note that your first line

 let assetUrl = NSURL.URLWithString(self.targetVideoString) 

no longer compiles with current Xcode 6.1.

+18
source

With Swift2.0, imageGenerator.copyCGImageAtTime is now tagged with throws, so you need to handle errors in the do-try-catch block.

  let asset : AVAsset = AVAsset(URL: yourNSURLtoTheAsset ) let imageGenerator = AVAssetImageGenerator(asset: asset) let time = CMTimeMakeWithSeconds(0.5, 1000) var actualTime = kCMTimeZero var thumbnail : CGImageRef? do { thumbnail = try imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime) } catch let error as NSError { print(error.localizedDescription) } 
+5
source

At least Xcode 7.0.1 and Swift 2 assetwithURL now: let asset = AVAsset(URL: assetURL) . Xcode error: "assetWithURL" unavailable: use the "AVAsset (URL :)" object construct

+2
source

Accepted answer in Swift 3:

 let asset = AVURLAsset(url: URL(fileURLWithPath: "YOUR_URL_STRING_HERE")) let imgGenerator = AVAssetImageGenerator(asset: asset) var cgImage: CGImage? do { cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil) } catch let error as NSError { // Handle the error print(error) } // Handle the nil that cgImage might be let uiImage = UIImage(cgImage: cgImage!) 
0
source

Source: https://habr.com/ru/post/977851/


All Articles