iOS视频转换

iOS原生照片库视频格式为.mov,内存占用大,在发送文件中对它进行压缩为mp4。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
- (void)movFileTransformToMP4WithSourcePath:(NSString *)sourcePath completion:(void(^)(NSString *Mp4FilePath))comepleteBlock session:(void(^)(AVAssetExportSession *session))sessionBlock
{
/**
* mov格式转mp4格式
*/
NSURL *sourceUrl = [NSURL URLWithString:sourcePath];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:sourceUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
NSString *fileStr = [[sourcePath componentsSeparatedByString:@"/"].lastObject.uppercaseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fileName = [[fileStr componentsSeparatedByString:@"."].firstObject.uppercaseString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *uniqueName = [NSString stringWithFormat:@"%@.mp4",fileName];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = docPaths.lastObject;
NSString * resultPath = [docPath stringByAppendingPathComponent:uniqueName];
exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse = YES;
//如有此文件则直接返回
if ([[NSFileManager defaultManager] fileExistsAtPath:resultPath]) {
comepleteBlock(resultPath);
return;
}
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusUnknown:
{
NSLog(@"视频格式转换出错Unknown");
sessionBlock(exportSession);
}
break;
case AVAssetExportSessionStatusWaiting:
{
NSLog(@"视频格式转换出错Waiting");
sessionBlock(exportSession);
}
break;
case AVAssetExportSessionStatusExporting:
{
NSLog(@"视频格式转换出错Exporting");
sessionBlock(exportSession);
}
break;
case AVAssetExportSessionStatusCompleted:
{
comepleteBlock(resultPath);
NSLog(@"mp4 file size:%lf MB",[NSData dataWithContentsOfURL:exportSession.outputURL].length/1024.f/1024.f);
NSData *da = [NSData dataWithContentsOfFile:resultPath];
NSLog(@"da:%lu",(unsigned long)da.length);
}
break;
case AVAssetExportSessionStatusFailed:
{
NSLog(@"视频格式转换出错Unknown");
sessionBlock(exportSession);
}
break;
case AVAssetExportSessionStatusCancelled:
{
NSLog(@"视频格式转换出错Cancelled");
sessionBlock(exportSession);
}
break;
}
}];
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!