问题
I'm creating video thumbnails with the following code and it works in most cases. However sometimes it throws an error and the thumbnail is not created. I can't figure out why it does not work sometimes.
Here is how I create video thumbnail:
let asset = AVAsset(URL: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
do {
let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(1, 30), actualTime: nil)
let uiImage = UIImage(CGImage: cgImage)
imageview.image = uiImage
}
catch let error as NSError
{
print("Image generation failed with error \(error)")
}
It works in most cases, when it does not work it throws this error:
Error generating thumbnail: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x17658520 {Error Domain=NSOSStatusErrorDomain Code=-12792 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12792)}
I have no clue why it throws this error and did not find any solution on stack overflow even though other people faced same problem.
回答1:
Try this.
func generateThumbnail(path: URL) -> UIImage? {
do {
let asset = AVURLAsset(url: path, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
return thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
return nil
}
}
来源:https://stackoverflow.com/questions/37374008/ios-swift-video-thumbnail-error