我想在特定时间从视频中抓取帧。我正在将我的抓取帧函数调用为Float64,将时间指定为秒。问题在于它没有抓取当前帧。似乎忽略了小数点。如果我用例如1.22和1.70调用该函数,它将返回同一帧。关于Swift,我是一个新手,所以我想我没有正确使用CMTime对象。那么,谁能看到这是怎么回事?
func generateThumnail(url : NSURL, fromTime:Float64) -> UIImage { var asset :AVAsset = AVAsset.assetWithURL(url) as! AVAsset var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true var error : NSError? = nil var time : CMTime = CMTimeMakeWithSeconds(fromTime, 600) var img : CGImageRef = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: &error) var frameImg : UIImage = UIImage(CGImage: img)! return frameImg } var grabTime = 1.22 img = generateThumnail(urlVideo, fromTime: Float64(grabTime))
我设法找出添加:
assetImgGenerate.requestedTimeToleranceAfter = kCMTimeZero; assetImgGenerate.requestedTimeToleranceBefore = kCMTimeZero;
…对我的职能将达到目的。
我更新的函数如下所示:
func generateThumnail(url : NSURL, fromTime:Float64) -> UIImage { var asset :AVAsset = AVAsset.assetWithURL(url) as! AVAsset var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true assetImgGenerate.requestedTimeToleranceAfter = kCMTimeZero; assetImgGenerate.requestedTimeToleranceBefore = kCMTimeZero; var error : NSError? = nil var time : CMTime = CMTimeMakeWithSeconds(fromTime, 600) var img : CGImageRef = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: &error) var frameImg : UIImage = UIImage(CGImage: img)! return frameImg } var grabTime = 1.22 img = generateThumnail(urlVideo, fromTime: Float64(grabTime))