Created
August 11, 2020 09:10
-
-
Save dharmeshrchauhan/30e5a0df7d7715bc801c53b2cb9a049a to your computer and use it in GitHub Desktop.
swift code for cropVideo (swift 5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func cropVideo(_ inputFileUrl: URL, outputFileUrl: URL, rect: CGRect, completion: @escaping () -> Void) | |
{ | |
// Get input clip | |
//let videoAsset: AVAsset = AVAsset( url: inputFileUrl ) | |
let videoAsset: AVURLAsset = AVURLAsset(url: inputFileUrl, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true]) | |
let clipVideoTrack = videoAsset.tracks( withMediaType: AVMediaType.video ).first! as AVAssetTrack | |
let videoComposition: AVMutableVideoComposition = AVMutableVideoComposition() | |
videoComposition.frameDuration = clipVideoTrack.minFrameDuration | |
videoComposition.renderSize = CGSize(width: rect.size.width, height: rect.size.height) | |
let instruction: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction() | |
instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration) | |
let transformer: AVMutableVideoCompositionLayerInstruction = | |
AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack) | |
let t1: CGAffineTransform = CGAffineTransform(translationX: -rect.origin.x, y: -rect.origin.y) | |
transformer.setTransform(t1, at: CMTime.zero) | |
instruction.layerInstructions = [transformer] | |
videoComposition.instructions = [instruction] | |
let exporter = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)! | |
exporter.videoComposition = videoComposition | |
exporter.outputFileType = AVFileType.mov | |
exporter.outputURL = outputFileUrl | |
exporter.exportAsynchronously { | |
completion() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment