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"];
//創(chuàng)建目錄
NSString *createPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
// 判斷文件夾是否存在,如果不存在,則創(chuàng)建
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.對視頻進(jìn)行壓縮
- (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(@"視頻轉(zhuǎn)碼成功");
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];
}