注意:需要判断之前的文件是否存在 ,如果存在则删除文件 [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
- (void)convertVideoWithModel
{
[self creatSandBoxFilePathIfNoExist];
//保存至沙盒路径
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *videoPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
//转码配置
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:self.videoURL options:nil];
//AVAssetExportPresetMediumQuality可以更改,是枚举类型,官方有提供,更改该值可以改变视频的压缩比例
AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputURL = [NSURL fileURLWithPath:[videoPath stringByAppendingPathComponent:@"fourmVideo.mp4"]];
//AVFileTypeMPEG4 文件输出类型,可以更改,是枚举类型,官方有提供,更改该值也可以改变视频的压缩比例
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
[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);
NSData *videoData = [NSData dataWithContentsOfURL:self.videoURL];
self.loadVideoData(self.videoURL,videoData);
break;
}
case AVAssetExportSessionStatusCompleted:
{
NSLog(@"视频转码成功");
NSData *videoData = [NSData dataWithContentsOfFile:[videoPath stringByAppendingPathComponent:@"fourmVideo.mp4"]];
self.loadVideoData(_videoURL,videoData);
}
}
}];
}
- (void)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];
//创建目录
NSString *createPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
// 判断文件夹是否存在,如果不存在,则创建
if ([[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
NSError *error;
if ([[NSFileManager defaultManager] removeItemAtPath:createPath error:&error] == NO) {
NSLog(@"removeitematpath %@ error :%@", createPath, error);
}
}
[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
}