How do I implement AVAssetImageGenerator.copyCGImageAtTime in swift

user379468 picture user379468 · Nov 6, 2014 · Viewed 9.9k times · Source

Thus 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 simply want to grab an image at time 1.0 seconds

Answer

Martin R picture Martin R · Nov 6, 2014

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

Note also that your first line

let assetUrl = NSURL.URLWithString(self.targetVideoString)

does not compile anymore with the current Xcode 6.1.