iOS AVAssetExportSession视频进行转码、裁剪

来源:互联网 发布:sql insert into 多表 编辑:程序博客网 时间:2024/05/24 07:02

你可以对视频进行转码、裁剪,通过使用AVAssetExportSession对象。这个流程如下图所示,

一个export session是一个控制对象,可以异步的生成一个asset。可以用你需要生成的asset和presetName来初始化一个session,presetName指明你要生成的asset的属性。接下来你可以配置export session,比如可以指定输出的URL和文件类型,以及其他的设置,比如metadata等等。你可以先检测设置的preset是否可用,通过使用exportPresetsCompatibleWithAsset:方法。

AVAsset *anAsset = <#Get an asset#>;NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]        initWithAsset:anAsset presetName:AVAssetExportPresetLowQuality];    // Implementation continues.}

你可以配置session的输出的url(这个url必须是文件url),AVAssetExportSession可以推断通过url的扩展名出输出文件的类型。当然,你可以直接设置文件类型,使用outputFileType。你还可以指定其他属性,比如time range,输出文件的长度等等,下面是列子:

exportSession.outputURL = <#A file URL#>;    exportSession.outputFileType = AVFileTypeQuickTimeMovie;    CMTime start = CMTimeMakeWithSeconds(1.0, 600);    CMTime duration = CMTimeMakeWithSeconds(3.0, 600);    CMTimeRange range = CMTimeRangeMake(start, duration);    exportSession.timeRange = range;

生成一个新的asset,可以调用exportAsynchronouslyWithCompletionHandler:,当生成操作结束后会回调block,在这个block中你需要通过检查session的status来判断是否成功,如下:

  [exportSession exportAsynchronouslyWithCompletionHandler:^{        switch ([exportSession status]) {            case AVAssetExportSessionStatusFailed:                NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);                break;            case AVAssetExportSessionStatusCancelled:                NSLog(@"Export canceled");                break;            default:                break;        }    }];

你可以取消这个生成操作,通过给session发送 cancelExport 消息。如果导出的文件存在,或者导出的url在沙盒之外,这个导出操作会失败。还有两种情况也可能导致失败:· 来了一个电话· 你的程序在后台运行并且其他的应用开始播放。这种情况下,你应该通知用户export失败,并且重新export。

原创粉丝点击