我无法生成1秒视频的缩略图。我试过下面的代码,但它每次都会生成黑色图像。我已经尝试将时间刻度传递为(0,30(,(0,1(。如果视频超过1.5秒,它就会工作。
static func thumbnailFromVideo(videoUrl: URL, time: CMTime) -> UIImage {
let asset: AVAsset = AVAsset(url: videoUrl) as AVAsset
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
do {
let cgImage = try imgGenerator.copyCGImage(at: time, actualTime: nil)
let uiImage = UIImage(cgImage: cgImage)
return uiImage
} catch {
}
return UIImage()
}
如果您需要一个帧准确的缩略图,您需要将前后请求的时间公差设置为零:
来自文档:
将requestedTimeToleranceBefore和requestedTimeToleranceAfter的值设置为零,以请求帧精确的图像生成;这可能导致额外的解码延迟。
imgGenerator.requestedTimeToleranceBefore = .zero
imgGenerator.requestedTimeToleranceAfter = .zero
这对我有用。
func getvideosnapshot(url : URL , completion : @escaping ((UIImage?) ->())){
DispatchQueue.global().async {
let asset: AVAsset = AVAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
let timestamp = CMTime(value: 1, timescale: 600)
do {
let thumbnail = try imageGenerator.copyCGImage(at: timestamp, actualTime: nil)
DispatchQueue.main.async {
completion(UIImage(cgImage: thumbnail))
}
} catch let err as NSError {
// print(err)
completion(nil)
}
}
}