Created
July 10, 2019 13:25
-
-
Save atereshkov/01b35e60b5f1c381b3050e78d2ab5541 to your computer and use it in GitHub Desktop.
VideoCompression AVFoundation
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
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