首页 > 解决方案 > 如果视频来自本地库文件夹,则视频缩略图生成失败

问题描述

使用iOS14.5、Swift5.4、Xcode12.5、

我尝试在 Swift 中创建视频的缩略图。

这一切都适用于源自互联网的视频。

但是,在我的情况下,视频来自应用程序的库文件夹,它预先保存在该文件夹中。由于某种未知原因,这似乎使缩略图创建失败。

这是我的步骤:

  1. 我首先通过执行以下操作将视频从捆绑包复制到 iPhone 沙盒的库文件夹(videoURL 是本地库文件夹中的某个位置)
guard fileManager.fileExists(atPath: videoURL.path) else {
    guard let video = NSDataAsset(name: videoName)  else { return nil }
    fileManager.createFile(atPath: videoURL.path, contents: video.data, attributes: nil)
}
  1. 然后我尝试通过以下代码生成缩略图。

但是此代码总是失败并出现以下错误:

VideoThumb image generation failed with error Error Domain=AVFoundationErrorDomain 
Code=-11850 "Operation Stopped" UserInfo={NSLocalizedFailureReason=The server is not 
correctly configured., NSLocalizedDescription=Operation Stopped, 
NSUnderlyingError=0x2817da100 {Error Domain=NSOSStatusErrorDomain Code=-12939 "(null)"}}

这里是缩略图生成的代码:

private func generateThumbImage(for videoURL: URL) -> UIImage? {
        
    let asset = AVAsset(url: videoURL)
    
    let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.apertureMode = .encodedPixels
    let time = CMTimeMake(value: 50, timescale: 60)
    do {
        let imageRef = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        return UIImage(cgImage: imageRef)
    }
    catch {
        !!!!!!!!!!!!!!!!!!!!!!!!!!! Always hit this catch here - WHY ???????????????????????
        print("VideoThumb image generation failed with error \(error)")
        return nil
    }
}

标签: thumbnailsavassetavassetimagegenerator

解决方案


我终于找到了解决方案:

您需要file:在本地 URL 之前添加

这里是调用缩略图生成的工作代码:

if let vidThumb = generateThumbnail(videoURL: URL(string: "file:" + url.absoluteString)!) { ... }


推荐阅读