美文网首页
swift: 记录截取本地视频最后一帧

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

作者: 小曼blog | 来源:发表于2019-01-05 14:51 被阅读24次

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

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: 记录截取本地视频最后一帧

      本文链接:https://www.haomeiwen.com/subject/ilgrrqtx.html