业务需求:移动端拍摄视频并上传。
问题:使用系统自带的拍摄组件UIImagePicker拍摄的视频为苹果公司特有的.mov格式文件,上传到服务器端后,使用安卓客户端播放视频的效果并不友好。
解决方法:视频统一转换为MPEG4格式后再上传
代码示例:
- (void)movFileTransformToMP4WithSourceUrl:(NSURL *)sourceUrl completion:(void(^)(NSString *Mp4FilePath))comepleteBlock
{
/**
* mov格式转mp4格式
*/
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:sourceUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
NSLog(@"%@",compatiblePresets);
if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *uniqueName = [NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]];
NSString * resultPath = [PATH_OF_DOCUMENT stringByAppendingPathComponent:uniqueName];//PATH_OF_DOCUMENT为documents路径
NSLog(@"output File Path : %@",resultPath);
exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
exportSession.outputFileType = AVFileTypeMPEG4;//可以配置多种输出文件格式
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
dispatch_async(dispatch_get_main_queue(), ^{
[hud hideAnimated:YES];
});
switch (exportSession.status) {
case AVAssetExportSessionStatusUnknown:
// NSLog(@"AVAssetExportSessionStatusUnknown");
CLOUDMESSAGETIPS(@"视频格式转换出错Unknown", 0.8); //自定义错误提示信息
break;
case AVAssetExportSessionStatusWaiting:
// NSLog(@"AVAssetExportSessionStatusWaiting");
CLOUDMESSAGETIPS(@"视频格式转换出错Waiting", 0.8);
break;
case AVAssetExportSessionStatusExporting:
// NSLog(@"AVAssetExportSessionStatusExporting");
CLOUDMESSAGETIPS(@"视频格式转换出错Exporting", 0.8);
break;
case AVAssetExportSessionStatusCompleted:
{
// NSLog(@"AVAssetExportSessionStatusCompleted");
comepleteBlock(resultPath);
NSLog(@"mp4 file size:%lf MB",[NSData dataWithContentsOfURL:exportSession.outputURL].length/1024.f/1024.f);
}
break;
case AVAssetExportSessionStatusFailed:
// NSLog(@"AVAssetExportSessionStatusFailed");
CLOUDMESSAGETIPS(@"视频格式转换出错Unknown", 0.8);
break;
case AVAssetExportSessionStatusCancelled:
// NSLog(@"AVAssetExportSessionStatusFailed");
CLOUDMESSAGETIPS(@"视频格式转换出错Cancelled", 0.8);
break;
}
}];
}
}