Tejas Patel Tejas Patel - 3 months ago 21
Objective-C Question

iOS Convert AVI to MP4 Format programatically

I have one query in my application, for that i want to convert my AVI formatted video to MP4 movie format, so is there any way to do this programatically.

Any code snippet will be appreciated.

Answer

You need to use AVAssetExportSession to convert videos to .mp4 format, below method convert .avi format videos to .mp4.

Check the line exportSession.outputFileType = AVFileTypeMPEG4; it specify the output format of the video.

Here inputURL is an url of video which needs to be converted and outputURL will be the final destination of video.

One more thing don't forget to specify .mp4 extension in outputURL video file.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyVideo.mp4"];
NSURL *outputURL = [NSURL fileURLWithPath:filePath];

[self convertVideoToLowQuailtyWithInputURL:localUrl outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
{
    if (exportSession.status == AVAssetExportSessionStatusCompleted) {
        // Video conversation completed
    }          
}];

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL handler:(void (^)(AVAssetExportSession*))handler {
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
         handler(exportSession);
     }];
}