AVAsset *asset = [AVAsset assetWithURL:sourceURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(1, 1);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef); // CGImageRef won't be released by ARC
雨燕**
var asset = AVAsset.assetWithURL(sourceURL)
var imageGenerator = AVAssetImageGenerator(asset: asset!)
var time = CMTimeMake(1, 1)
var imageRef = try! imageGenerator!.copyCGImageAtTime(time, actualTime: nil)
var thumbnail = UIImage.imageWithCGImage(imageRef)
CGImageRelease(imageRef) // CGImageRef won't be released by ARC
雨燕3.0**
var sourceURL = URL(string: "Your Asset URL")
var asset = AVAsset(url: sourceURL!)
var imageGenerator = AVAssetImageGenerator(asset: asset)
var time = CMTimeMake(1, 1)
var imageRef = try! imageGenerator.copyCGImage(at: time, actualTime: nil)
var thumbnail = UIImage(cgImage:imageRef)
let asset = AVAsset(...)
let imageGenerator = AVAssetImageGenerator(asset: asset)
let screenshotTime = CMTime(seconds: 1, preferredTimescale: 1)
if let imageRef = try? imageGenerator.copyCGImageAtTime(screenshotTime, actualTime: nil) {
let image = UIImage(CGImage: imageRef)
// do something with your image
}
seconds = .. the normal human-meaning desired time position in the video
guard let pl = .. your player ..
guard let ite = pl.currentItem ..
let testGen = AVAssetImageGenerator(asset: ite.asset)
testGen.maximumSize = CGSize(width: 0, height: .. height of your preview box)
testGen.requestedTimeToleranceBefore = .zero // during development
// or something like ... CMTime(value: .. your tolerance .., timescale: 600)
testGen.requestedTimeToleranceAfter = .zero // during development
// ditto
if #available(tvOS 16, *) {
Task { [weak self] ..
do {
let ct = CMTime(value: CMTimeValue(seconds), timescale: 1)
// NOTE THE "1"
let (foundImage, foundTime) = try await testGen.image(at: ct)
let foundAsSecs = CMTimeGetSeconds(foundTime)
print("tried gen at \(seconds) found as \(foundAsSecs) \n")
self. .. your preview .image = UIImage(cgImage: foundImage)
} catch {
print("gen err \(error)")
}
}
}
8条答案
按热度按时间oiopk7p51#
rn0zuynd2#
试试这个
希望这对你有帮助!
wqsoz72f3#
斯威夫特2.x:
ct3nt3jp4#
添加以下代码,从视频生成缩略图。
h7wcgrx35#
这是我如何在Swift中获取场景中当前可见帧的镜头:
关键在于
1.获取类型为
CMTime
的播放器的当前时间1.将该时间转换为
Float64
类型的秒1.使用
CMTimeMake
将secondss切换回CMTime
。第一个参数(即秒的位置)应强制转换为Int64
代码:
xggvc2p66#
用于从视频生成缩略图的Swift扩展
dgtucam17#
当你需要一次创建多个缩略图时,类
AVAssetImageGenerator
是最好的,因为它提供了一种异步方式。如果您需要播放器当前帧的缩略图图像,只需渲染其视图(特定于平台)或其层(独立于平台):
这是超快和同步工作。
yc0p9oo08#
2022年代码:
谷歌称,设定这两个容差是一个复杂的问题。
注意其中CMTime需要
timescale
为1的陷阱。