Skip to content

Instantly share code, notes, and snippets.

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 atereshkov/01b35e60b5f1c381b3050e78d2ab5541 to your computer and use it in GitHub Desktop.
Save atereshkov/01b35e60b5f1c381b3050e78d2ab5541 to your computer and use it in GitHub Desktop.
VideoCompression AVFoundation
import Foundation
import AVFoundation
protocol VideoCompressorProtocol {
func compress(fileURL: URL, outputURL: URL, completion: @escaping (URL?, Error?) -> Void)
}
class VideoCompressor: VideoCompressorProtocol {
func compress(fileURL: URL, outputURL: URL, completion: @escaping (URL?, Error?) -> Void) {
if let data = try? Data(contentsOf: fileURL) {
print("LOG: File size before compression: \(Double(data.count / 1048576)) mb")
}
compressVideo(inputURL: fileURL, outputURL: outputURL) { compressedURL, error in
if let compressedURL = compressedURL, let data = try? Data(contentsOf: compressedURL) {
print("LOG: File size after compression: \(Double(data.count / 1048576)) mb")
}
completion(compressedURL, error)
}
}
private func compressVideo(inputURL: URL, outputURL: URL, completion: @escaping (URL?, Error?) -> Void) {
let urlAsset = AVURLAsset(url: inputURL, options: nil)
let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality)
exportSession?.outputURL = outputURL
exportSession?.outputFileType = AVFileType.mov
exportSession?.shouldOptimizeForNetworkUse = true
exportSession?.exportAsynchronously { () -> Void in
guard let exportSession = exportSession else { return }
if exportSession.status == .completed {
completion(outputURL, nil)
} else if exportSession.status == .failed {
completion(nil, exportSession.error)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment