swift: 记录截取本地视频最后一帧

思路:把视频分片,然后截取每一片截取图片,回调的是每一片中的一张图片。

private func getImage(url: URL, callback: @escaping (UIImage?) ->Void) {
        
        //1. 获取视频时长
        let urlAsset = AVURLAsset(url: url)
        let seconds = urlAsset.duration.seconds
        print("second: \(seconds)")
        
        //2. 截图配置
        let generator = AVAssetImageGenerator(asset: urlAsset)
        generator.appliesPreferredTrackTransform = true
        generator.maximumSize = playerView.bounds.size
        generator.requestedTimeToleranceBefore = .zero
        generator.requestedTimeToleranceAfter = .zero
        
        //3. 分段截图时间数组
        var times: [NSValue] = []
        for i in 1...Int(seconds) {
            let timeM = CMTimeMake(value: Int64(i), timescale: 1)
            let timeV = NSValue(time: timeM)
            times.append(timeV)
        }
        print("times: \(times), count: \(times.count)")
        
        //4. 开始截图
        generator.generateCGImagesAsynchronously(forTimes: times) {
            (requestedTime, cgimage, actualTime, result, error) in
            
            switch result {
            case .cancelled, .failed: callback(nil)
            case .succeeded:
                guard let image = cgimage else {
                    callback(nil)
                    return
                }
                let displayImage = UIImage(cgImage: image)
                callback(displayImage)
            }
        }
    }

你可能感兴趣的:(swift: 记录截取本地视频最后一帧)