如何在swift中实现AVAssetImageGenerator.copyCGImageAtTime

时间:2014-11-06 20:55:05

标签: swift avasset avassetimagegenerator

到目前为止,我有以下

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

最后一行是我迷路的地方......我只是想在1.0秒时抓图像

4 个答案:

答案 0 :(得分:18)

该函数声明为

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

您必须将(已初始化的)CMTimeNSError?变量作为“进出表达式”传递给&

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)

另请注意您的第一行

let assetUrl = NSURL.URLWithString(self.targetVideoString)
使用当前的Xcode 6.1,

不再编译。

答案 1 :(得分:6)

使用Swift2.0 imageGenerator.copyCGImageAtTime现在标有throws,因此你必须处理do-try-catch块中的错误。

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

答案 2 :(得分:2)

至少Xcode 7.0.1和Swift 2 assetwithURL现在是:let asset = AVAsset(URL: assetURL)。 Xcode错误是''assetWithURL'不可用:使用对象构造'AVAsset(URL :)'“

答案 3 :(得分:2)

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