iOS以编程方式将AVI转换为MP4格式

时间:2015-09-04 06:05:06

标签: ios objective-c

我的应用程序中有一个查询,因为我想将AVI格式的视频转换为MP4电影格式,所以有没有办法以编程方式执行此操作。

任何代码段都将受到赞赏。

2 个答案:

答案 0 :(得分:4)

您需要使用AVAssetExportSession将视频转换为.mp4格式,以下方法将.avi格式视频转换为.mp4

检查行exportSession.outputFileType = AVFileTypeMPEG4;,指定视频的输出格式。

此处inputURL是需要转换的视频网址,outputURL将成为视频的最终目的地。

不要忘记在.mp4视频文件中指定outputURL个扩展名。

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);
     }];
}

答案 1 :(得分:1)

雨燕4.2

Swift 4.2 中接受的答案的更新版本。

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("MyVideo.mp4").absoluteString
let outputURL = URL(fileURLWithPath: filePath)
convertVideoToLowQuailty(withInputURL: inputUrl, outputURL: outputURL, handler: { exportSession in
    if exportSession?.status == .completed {
        // Video conversation completed
    }
})

func convertVideoToLowQuailty(withInputURL inputURL: URL?, outputURL: URL?, handler: @escaping (AVAssetExportSession?) -> Void) {
    if let anURL = outputURL {
        try? FileManager.default.removeItem(at: anURL)
    }
    var asset: AVURLAsset? = nil
    if let anURL = inputURL {
        asset = AVURLAsset(url: anURL, options: nil)
    }
    var exportSession: AVAssetExportSession? = nil
    if let anAsset = asset {
        exportSession = AVAssetExportSession(asset: anAsset, presetName: AVAssetExportPresetPassthrough)
    }
    exportSession?.outputURL = outputURL
    exportSession?.outputFileType = .mp4
    exportSession?.exportAsynchronously(completionHandler: {
        handler(exportSession)
    })
}

从在线转换tool获取帮助。