SWIFT 3 MP4 Video Compression
100 % Worked For Me
This code compress the video with URL(Document Directory) of 12 MB to 2 MB.
I have captured video with .mp4 format and compressed code returns video in same format.
Function where compress held
func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
let urlAsset = AVURLAsset(url: inputURL, options: nil)
guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality) else {
handler(nil)
return
}
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileTypeQuickTimeMovie // Don't change it to .mp4 format
exportSession.shouldOptimizeForNetworkUse = false
exportSession.exportAsynchronously { () -> Void in
handler(exportSession)
}
}
Code for Destination URL for Compressed Video
let filePath = URL(fileURLWithPath: strVideoPath)
var compressedURL : URL!
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:true)
compressedURL = documentDirectory.appendingPathComponent("Video.mp4")
} catch {
print(error)
}
//It is compulsory to remove previous item at same URL. Otherwise it is unable to save file at same URL.
do {
try fileManager.removeItem(at: compressedURL)
print("Removed")
} catch {
print(error)
}
Code For Calling
compressVideo(inputURL: filePath , outputURL: compressedURL) { (exportSession) in
guard let session = exportSession else {
return
}
switch session.status {
case .unknown:
break
case .waiting:
break
case .exporting:
break
case .completed:
print(compressedURL)
let newData : Data!
do {
newData = try Data(contentsOf: compressedURL) as Data?
print("File size after compression: \(Double((newData?.count)! / 1048576)) mb")
} catch {
return
}
case .failed:
print(exportSession?.error.debugDescription)
break
case .cancelled:
break
}
}