无法从图库中的视频生成缩略图

Unable to generate thumbnail from video in gallery

我向用户显示一个图像选择器,用于 select 图库中的视频。这行得通,我传递了媒体类型 ["public.movie"] 并且显示了画廊的所有视频以供选择。当用户选择它时,我在我的委托中收到:

extension VNInventoryCollectionVC: UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
        if let pickedImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage
        {
            pickImageCallback?(pickedImage)
        }
        if let videoURL = info["UIImagePickerControllerReferenceURL"] as? URL
        {
            print(videoURL)
            pickImageCallback?(videoURL)
        }
        dismiss(animated: true)
       
    }
}

回调后,我试图从该视频创建图像缩略图,但我无法做到这一点:

let thumbnail = getThumbnailFrom(path: multimedia.video!)
cell.image.image = thumbnail

生成缩略图的函数是:

func getThumbnailFrom(path: URL) -> UIImage? {
    do {
        print("Video URL: \(path)")
        print("Video absolute URL: \(path.absoluteURL)")
        //let asset = AVURLAsset(url: path.absoluteURL! , options: nil)
        var asset : AVAsset = AVAsset(url: path.absoluteURL) as! AVAsset
        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true
        let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
        let thumbnail = UIImage(cgImage: cgImage)

        return thumbnail

    } catch let error {
        print("*** Error generating thumbnail: \(error.localizedDescription)")
        return nil
    }
}

在控制台中显示的视频 url 是:

Video URL: assets-library://asset/asset.MP4?id=84D1CEDD-7AE4-4FE5-897E-47608DC2CFF0&ext=MP4
Video absolute URL: assets-library://asset/asset.MP4?id=84D1CEDD-7AE4-4FE5-897E-47608DC2CFF0&ext=MP4

显示的错误是无法打开文件。中断的行是:

let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)

我想问题出在 url,我有一个资产 url,我需要一个绝对文件路径或类似的东西。

使用UIImagePickerController.InfoKey.mediaURL键入信息字典。 UIImagePickerController.InfoKey.referenceURLdeprecated.

func didSelectVideo(at url: URL) {
    let asset = AVAsset(url: url)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true
    let cgImage = try! generator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
    let thumbnail = UIImage(cgImage: cgImage)
    cell.image.image = thumbnail
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    dismiss(animated: true) {
        guard let url = info[.mediaURL] as? URL else { return }
        self.didSelectVideo(at: url)
    }
}