如何将 AVMutableVideoComposition 转换为 AVAsset

How to convert an AVMutableVideoComposition to an AVAsset

我正在做一些视频编辑,我需要将我正在操作的 AVMutableVideoComposition 放回播放器项目中。要进入播放器项目,它需要是一个 AVAsset。如何做到这一点?

您可以使用 AVMutableComposition 作为 AVPlayerItem 的资产,因为 AVMutableCompositionAVAsset 的子类。

AVMutableVideoComposition 不是 AVAsset 的子类,而是一种在 AVMutableComposition 中显示您插入 AVAssetTracks 的视频的方式。

(如果您的所有视频都按照您喜欢的方式放置,而没有 AVMutableVideoComposition,那么您可能不需要设置播放器项目的 videoComposition 属性)

ObjC:

AVMutableComposition *composition = ...
AVMutableVideoComposition *videoComposition = ...
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:composition];
item.videoComposition = videoComposition;

Swift:

let composition = AVMutableComposition(...
let videoComposition = AVMutableVideoComposition(...
let item = AVPlayerItem(asset: composition)
item.videoComposition = videoComposition

勾选这个- exportPath 可以是任何保存视频的临时路径。

    func ConvertAvcompositionToAvasset(avComp: AVComposition, completion:@escaping (_ avasset: AVAsset) -> Void){
        let exporter = AVAssetExportSession(asset: avComp, presetName: AVAssetExportPresetHighestQuality)
        let randNum:Int = Int(arc4random())
        //Generating Export Path
        let exportPath: NSString = NSTemporaryDirectory().appendingFormat("\(randNum)"+"video.mov") as NSString
        let exportUrl: NSURL = NSURL.fileURL(withPath: exportPath as String) as NSURL
        //SettingUp Export Path as URL
        exporter?.outputURL = exportUrl as URL
        exporter?.outputFileType = AVFileTypeQuickTimeMovie
        exporter?.shouldOptimizeForNetworkUse = true
        exporter?.exportAsynchronously(completionHandler: {() -> Void in
            DispatchQueue.main.async(execute: {() -> Void in
                if exporter?.status == .completed {
                    let URL: URL? = exporter?.outputURL
                    let Avasset:AVAsset = AVAsset(url: URL!)
                    completion(Avasset)
                }
                else if exporter?.status == .failed{
                    print("Failed")

                }
            })
        }) }