大概你们大多数人都使用WhatsApp,你可能知道当你想要向你的某个联系人发送视频时,WhatsApp首先将视频压缩到最大16mb的大小,然后才会将所选视频上传到你的联系人。
我想要做的就是使用AV Foundation或更具体的AVAssetExportSession。
这是我的代码:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *videoURL = info[UIImagePickerControllerMediaURL];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath =[documentsDirectory stringByAppendingString:@"/output.mov"];
NSURL *outputURL = [NSURL fileURLWithPath:sourcePath];
[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
{
if (exportSession.status == AVAssetExportSessionStatusCompleted)
{
NSLog(@"completed");
}
else
{
NSLog(@"error: %@",exportSession.error);
}
}];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (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:AVAssetExportPresetMediumQuality];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
handler(exportSession);
}];
}
这段代码效果很好,它需要视频并将其压缩得非常小。
问题是,当用户尝试使用功能强大的相机上传相当长的视频时,其尺寸对我来说不够小。
我想要做的是将任何视频压缩到有限的大小 比如像WhatsApp那样以16Mb为例。 我该怎么做?
答案 0 :(得分:3)
似乎没有一种简单的方法,但AVAssetExportSession有一个可能有帮助的estimatedOutputFileLenght。
在我的代码中,我迭代不同的质量并检查文件大小是否符合我想要的大小:
NSURL * inputURL = [NSURL fileURLWithPath:path];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = nil;
for (NSString * string in @[AVAssetExportPresetHighestQuality,AVAssetExportPresetMediumQuality,AVAssetExportPresetLowQuality]) {
exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:string];
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
unsigned long long espectedFileSize = exportSession.estimatedOutputFileLength;
if (espectedFileSize < VIDE_LIMIT) {
break;
}
}
//Temp file
NSString *fileName = [NSString stringWithFormat:@"%@_%@", [[NSProcessInfo processInfo] globallyUniqueString], @"video.mov"];
NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
exportSession.outputURL = fileURL;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)