1.生成保存文件路径
- (NSString *)creatSandBoxFilePathIfNoExist
{
//沙盒路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSLog(@"databse--->%@",documentDirectory);
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSDateFormatter *formater = [[NSDateFormatter alloc] init];// 用时间, 给文件重新命名, 防止视频存储覆盖,
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
//创建目录
NSString *createPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
} else {
NSLog(@"FileImage is exists.");
}
NSString *resultPath = [createPath stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mov", [formater stringFromDate:[NSDate date]]]];
NSLog(@"%@",resultPath);
return resultPath;
}
2.对视频进行压缩
- (void)yaSuoShiPinWithfilepath:(NSURL *)filepath {
NSString *outPath = [self creatSandBoxFilePathIfNoExist];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:filepath options:nil];
AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputURL = [NSURL fileURLWithPath:outPath];
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
int exportStatus = exportSession.status;
// NSLog(@"%d",exportStatus);
switch (exportStatus)
{
case AVAssetExportSessionStatusFailed:
{
// log error to text view
NSError *exportError = exportSession.error;
NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
break;
}
case AVAssetExportSessionStatusCompleted:
{
NSLog(@"视频转码成功");
NSData *data = [NSData dataWithContentsOfFile:outPath];
imageShowCollectModel *model = [[imageShowCollectModel alloc] init];
model.picImage = [self firstFrameWithVideoURL:filepath size:CGSizeMake(80, 80)];;
model.type = @"video";
model.videoData = data;
[self.dataSource addObject:model];
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:^{}];
});
}
}
}];
[self.imageCollectView reloadData];
}