2017-10-09 202 views
0

我想從一個視頻的所有幀,但它總是在AVFoundation:copyCGImageAtTime總是返回零

cgImage = try assetImgGenerate.copyCGImageAtTime(time, actualTime: nil) 

我當前的代碼無法在這個樣子的

if let path = NSBundle.mainBundle().resourcePath { 
     let fullPath = path + "/mov/watch_phone.mov" 
     let url = NSURL(fileURLWithPath: fullPath) 
     mutableVideoURL = url 
     getFrame() 
     print(videoFrames.count) 
    } 

func getFrame() { 
    let asset:AVAsset = AVAsset(URL:self.mutableVideoURL as NSURL) 
    let assetImgGenerate:AVAssetImageGenerator = AVAssetImageGenerator(asset:asset) 
    assetImgGenerate.appliesPreferredTrackTransform = true 
    let duration:Float64 = CMTimeGetSeconds(asset.duration) 
    let durationInt:Int = Int(duration) 

    for index:Int in 0 ..< durationInt 
    { 
     generateFrames(assetImgGenerate, fromTime: Float64(index)) 
    } 
} 

func generateFrames(assetImgGenerate:AVAssetImageGenerator, fromTime:Float64) 
{ 
    let time:CMTime = CMTimeMakeWithSeconds(fromTime, 600) 
    let cgImage:CGImage? 

    do 
    { 
     cgImage = try assetImgGenerate.copyCGImageAtTime(time, actualTime: nil) 
     let frameImg:UIImage = UIImage(CGImage:cgImage!) 
     videoFrames.append(frameImg) 
    } 
    catch let error as NSError { 

     print("Found error in saving entity changes \(error)") 
    } 

copyCGImageAtTime總是返回零。 該視頻已添加到我的包中,並且也顯示在「構建階段」中的包資源中。

這是在catch塊收到錯誤

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x1700563e0 {Error Domain=NSOSStatusErrorDomain Code=-12430 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12430), NSLocalizedDescription=The operation could not be completed} 

請幫助我瞭解我在做什麼錯在這裏

回答

0

這是一個工作代碼。試試這個,並確保你有非零資產,正確的時間。

- (UIImage *)getUIImageOfVideoAsset:(AVAsset *)asset atTime:(CMTime)time withSize:(CGSize)size { 

NSError *error; 
AVAssetImageGenerator *baseImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; 
baseImageGenerator.appliesPreferredTrackTransform = YES; 
baseImageGenerator.maximumSize = size; 

CGImageRef cgImage = [baseImageGenerator copyCGImageAtTime:time actualTime:NULL error:&error]; 
UIImage *image = [UIImage imageWithCGImage:cgImage]; 
CGImageRelease(cgImage); 

return image; 
}