Skip to content

Instantly share code, notes, and snippets.

@dharmeshrchauhan
Created August 11, 2020 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmeshrchauhan/30e5a0df7d7715bc801c53b2cb9a049a to your computer and use it in GitHub Desktop.
Save dharmeshrchauhan/30e5a0df7d7715bc801c53b2cb9a049a to your computer and use it in GitHub Desktop.
swift code for cropVideo (swift 5)
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