我正在尝试使用AVFoundation从URL的视频中获取缩略图,但是附件却出现了黑色空白图像。
视频URL为https://www.riptide.tv/app/assets/2/3/small_3001190658061_2.mp4
下面是我的代码:
func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {
let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
downloadedThumbnails.updateValue(thumbnail, forKey: imgName)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}
答案 0 :(得分:0)
如果您将代码更改为
func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {
let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(5), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}
那是5秒钟。您可以看到生成的缩略图。
这是因为AVAssetImageGenerator
在什么时候获取帧都非常灵活
func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {
let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
assetImgGenerate.requestedTimeToleranceAfter = .zero
assetImgGenerate.requestedTimeToleranceBefore = .zero
let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}
设置
assetImgGenerate.requestedTimeToleranceAfter = .zero
assetImgGenerate.requestedTimeToleranceBefore = .zero
确保获得准确的帧缩略图。