首页 文章

Swift4.2从视频中获取截图

提问于
浏览
0

在Swift 4.2中我试图从视频中截取屏幕截图

func thumbnailImageFor(fileUrl:URL) -> UIImage? {

        let asset = AVAsset(url: fileUrl)
        let assetImgGenerate = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true

        let time = CMTimeMakeWithSeconds(1.0, preferredTimescale: 600)
        do {
            let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
            let thumbnail = UIImage(cgImage: img)
            return thumbnail
        } catch {
            print(error)
            return nil
        }   
 }

But getting error:

错误域= AVFoundationErrorDomain代码= -11800“操作无法完成”UserInfo = {NSLocalizedFailureReason =发生未知错误(-12792),NSLocalizedDescription =操作无法完成,NSUnderlyingError = 0x600000f46580 {错误域= NSOSStatusErrorDomain代码= -12792“(null)”}}

video's url: https://firebasestorage.googleapis.com/v0/b/lailaichatapp.appspot.com/o/message_movies%2F8A61AC4E-4A08-4EC7-BC78-A5D861BE48C5.mov?alt=media&token=8906971d-59d7-4880-988e-135615c10f22

我错过了什么吗?

1 回答

  • 1

    我认为这可能与电影的文件类型有关,因为这有效:

    import UIKit
    import AVFoundation
    
    func thumbnailImageFor(fileUrl:URL) -> UIImage? {
    
        let video = AVURLAsset(url: fileUrl, options: [:])
        let assetImgGenerate = AVAssetImageGenerator(asset: video)
        assetImgGenerate.appliesPreferredTrackTransform = true
    
        let videoDuration:CMTime = video.duration
        let durationInSeconds:Float64 = CMTimeGetSeconds(videoDuration)
    
        let numerator = Int64(1)
        let denominator = videoDuration.timescale
        let time = CMTimeMake(value: numerator, timescale: denominator)
    
        do {
            let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
            let thumbnail = UIImage(cgImage: img)
            return thumbnail
        } catch {
            print(error)
            return nil
        }
    }
    
    let url: URL = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4")!
    
    let image: UIImage? = thumbnailImageFor(fileUrl: url)
    print("Image: \(image)")
    

相关问题