Created
January 29, 2019 13:23
-
-
Save Denismih/e8b5781b0eb8ce9ad758d6269854941d to your computer and use it in GitHub Desktop.
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 convertVideo(phAsset : PHAsset){ | |
PHImageManager.default().requestAVAsset(forVideo: phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in | |
if let asset = asset as? AVURLAsset { | |
do { | |
let videoData = try Data.init(contentsOf: asset.url) | |
print(asset.url) | |
self.orginalVideo = asset.url | |
print("File size before compression: \(Double(videoData.count / 1048576)) mb") | |
let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".MP4") | |
print(compressedURL) | |
self.compressVideo(inputURL: asset.url , outputURL: compressedURL) { (exportSession) in | |
guard let session = exportSession else { | |
return | |
} | |
switch session.status { | |
case .unknown: | |
print("unknown") | |
break | |
case .waiting: | |
print("waiting") | |
break | |
case .exporting: | |
print("exporting") | |
break | |
case .completed: | |
do { | |
let compressedData = try Data.init(contentsOf: compressedURL) | |
self.compressVideo = compressedURL | |
print(compressedData) | |
print("File size AFTER compression: \(Double(compressedData.count / 1048576)) mb") | |
} | |
catch{ | |
print(error) | |
} | |
case .failed: | |
print("failed") | |
break | |
case .cancelled: | |
print("cancelled") | |
break | |
} | |
} | |
} catch { | |
print(error) | |
//return | |
} | |
} | |
}) | |
} | |
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 = AVFileType.mp4 | |
exportSession.shouldOptimizeForNetworkUse = true | |
exportSession.exportAsynchronously { () -> Void in | |
handler(exportSession) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment