iOS: AVPlayer - getting a snapshot of the current frame of a video

前端 未结 2 1585
难免孤独
难免孤独 2020-12-14 22:42

I have spent the whole day and went through a lot of SO answers, Apple references, documentations, etc, but no success.

I want a simple thing: I am playing a

2条回答
  •  無奈伤痛
    2020-12-14 23:06

    AVAssetImageGenerator is the best way to snapshot a video, this method return asynchronously a UIImage :

    import AVFoundation
    
    // ...
    
    var player:AVPlayer? = // ...
    
    func screenshot(handler:@escaping ((UIImage)->Void)) {
        guard let player = player ,
            let asset = player.currentItem?.asset else {
                return
        }
    
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        let times = [NSValue(time:player.currentTime())]
    
        imageGenerator.generateCGImagesAsynchronously(forTimes: times) { _, image, _, _, _ in
            if image != nil {
                handler(UIImage(cgImage: image!))
            }
        }
    }
    

    (It's Swift 4.2)

提交回复
热议问题