Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement AVAssetImageGenerator.copyCGImageAtTime in swift

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

like image 568
user379468 Avatar asked Nov 06 '14 20:11

user379468


3 Answers

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.

like image 152
Martin R Avatar answered Nov 08 '22 05:11

Martin R


With Swift2.0 imageGenerator.copyCGImageAtTime is now marked with throws so you have to handle the errors in a 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)
    }
like image 6
Tim Bull Avatar answered Nov 08 '22 03:11

Tim Bull


Accepted answer in Swift 3, 4:

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!)
like image 4
Allen Avatar answered Nov 08 '22 05:11

Allen