具有修改的分辨率设置的AVAssetExportSession

时间:2016-04-19 22:36:03

标签: ios avfoundation avassetexportsession avkit

AVAssetExportSession将预设作为其初始化参数之一:

AVAssetExportSession(asset: AVAsset, presetName: String)

其中预设为AVAssetExportPreset640x480AVAssetExportPreset1920x1080等设置。但是,如果我想使用自定义分辨率(例如250x400)进行编码,有没有办法做到这一点,如果是这样的话?

2 个答案:

答案 0 :(得分:2)

这些导出选项已定义,无法允许您使用自定义分辨率进行编码。或者,您可以尝试这种方法

func exportVideo(asset:AVAsset, renderedWidth: CGFloat, renderedHeight: CGFloat, exportCompletionHandler: (() -> Void)?) {
        let videoTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0]

        let videoComposition = AVMutableVideoComposition()
        videoComposition.frameDuration = CMTimeMake(1, 30)
        videoComposition.renderSize = CGSizeMake(renderedWidth, renderedHeight)

        let instruction: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction.init()
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))

        let transformer: AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack);
        //Apply any transformer if needed
        //

        instruction.layerInstructions = [transformer]
        videoComposition.instructions = [instruction]

        //Create export path
        let exportPath: NSURL = NSURL(fileURLWithPath: "export_path_here")
        //

        let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
        exporter?.videoComposition = videoComposition
        exporter?.outputURL = exportPath
        exporter?.outputFileType = AVFileTypeQuickTimeMovie

        exporter?.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            //Do sth when finished
            if let handler = exportCompletionHandler {
                handler()
            }
        })
    }

我希望这会有所帮助。

参考:https://www.one-dreamer.com/cropping-video-square-like-vine-instagram-xcode/

答案 1 :(得分:0)

您可以使用自定义分辨率,使用AVAssetWriter而不是AVAssetExportSession进行调查。这个问题有一些相关的示例代码Record square video using AVFoundation and add watermark

另一个相当直接的替代方案是使用SDAVAssetExportSession https://github.com/rs/SDAVAssetExportSession来查看AVAssetExportSession的“drop in”替换,它需要一些额外的设置(在内部它只是AVAssetReader和AVssetWriter的实现包装看起来像AVAssetExportSession但另外公开了videoSettings和audioSettings选项。)