8

到目前为止,我有以下

  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

4 回答 4

19

该函数声明为

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 进行编译。

于 2014-11-06T21:12:02.823 回答
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)
    }
于 2016-03-03T19:26:36.173 回答
3

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!)
于 2018-03-21T17:42:25.847 回答
2

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

于 2015-10-08T22:42:25.213 回答