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
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.
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)
}
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!)
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