Last active
June 12, 2023 19:10
-
-
Save iAmrSalman/0f2624ef3f4982600f53a4c9f0201fb0 to your computer and use it in GitHub Desktop.
[Convert MOV to MP4] function to convert MOV to MP4 video format#swift #avkit #avasset
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
// Don't forget to import AVKit | |
func encodeVideo(at videoURL: URL, completionHandler: ((URL?, Error?) -> Void)?) { | |
let avAsset = AVURLAsset(url: videoURL, options: nil) | |
let startDate = Date() | |
//Create Export session | |
guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) else { | |
completionHandler?(nil, nil) | |
return | |
} | |
//Creating temp path to save the converted video | |
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL | |
let filePath = documentsDirectory.appendingPathComponent("rendered-Video.mp4") | |
//Check if the file already exists then remove the previous file | |
if FileManager.default.fileExists(atPath: filePath.path) { | |
do { | |
try FileManager.default.removeItem(at: filePath) | |
} catch { | |
completionHandler?(nil, error) | |
} | |
} | |
exportSession.outputURL = filePath | |
exportSession.outputFileType = AVFileType.mp4 | |
exportSession.shouldOptimizeForNetworkUse = true | |
let start = CMTimeMakeWithSeconds(0.0, 0) | |
let range = CMTimeRangeMake(start, avAsset.duration) | |
exportSession.timeRange = range | |
exportSession.exportAsynchronously(completionHandler: {() -> Void in | |
switch exportSession.status { | |
case .failed: | |
print(exportSession.error ?? "NO ERROR") | |
completionHandler?(nil, exportSession.error) | |
case .cancelled: | |
print("Export canceled") | |
completionHandler?(nil, nil) | |
case .completed: | |
//Video conversion finished | |
let endDate = Date() | |
let time = endDate.timeIntervalSince(startDate) | |
print(time) | |
print("Successful!") | |
print(exportSession.outputURL ?? "NO OUTPUT URL") | |
completionHandler?(exportSession.outputURL, nil) | |
default: break | |
} | |
}) | |
} |
Not working with latest iOS versions
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i got error with ios 16: