iOS开发 - 系统原生视频压缩处理方式
2017-12-15 本文已影响0人
阿唯不知道
需要导入:#import <AVFoundation/AVFoundation.h>
使用到的变量:
@property (nonatomic, strong) NSString * videoPath;//视频压缩处理后的路径
@property (nonatomic, strong) NSString * qualityPreset; //预设视频压缩画质
代码调用方式:
[self alertVideoHandleModel];
核心代码展示:
- (void)alertVideoHandleModel {
UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"视频选择" message:@"您可在相册中选择视频,也可以直接录制视频" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *chooseVideoAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self chooseVideo];
}];
UIAlertAction *recordVideoAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self startRecordVideo];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[actionSheet addAction:chooseVideoAction];
[actionSheet addAction:recordVideoAction];
[actionSheet addAction:cancelAction];
[self presentViewController:actionSheet animated:YES completion:nil];
}
#pragma mark *** Video Handling -------------- Start -------------- ***
// 选择本地视频
- (void)chooseVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
[self presentViewController:imagePicker animated:YES completion:nil];
imagePicker.delegate = self;
}
// 录制视频
- (void)startRecordVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
[self presentViewController:imagePicker animated:YES completion:nil];
// 最长拍摄 300秒(5分钟)
imagePicker.videoMaximumDuration = 5.0 * 60.0f;
imagePicker.delegate = self;
}
// 获取文件的大小,返回的是单位是MB。
- (CGFloat)getFileSize:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
float filesize = -1.0;
if ([fileManager fileExistsAtPath:path]) {
// 获取文件的属性
NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];
unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
filesize = 1.0*size/1024/1024;
} else {
NSLog(@"没有找到相关文件");
}
return filesize;
}
// 获取视频文件的时长。
- (CGFloat)getVideoLength:(NSURL *)URL {
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value / time.timescale);
return second;
}
// 获取视频第一帧图片
- (UIImage *)getFirstFrameWithVideoURL:(NSURL *)URL {
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:URL options:opts];
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
generator.appliesPreferredTrackTransform = YES;
generator.maximumSize = CGSizeMake(400, 200);
NSError *error = nil;
CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
if (!error) {
return [UIImage imageWithCGImage:img];
}
return nil;
}
// 删除导出后的视频
- (void)removeWithVideoPath:(NSString *)path {
// 删除文件
BOOL isDelete = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
if (!isDelete) {
NSLog(@"视频删除失败");
}
}
#pragma mark - <UIImagePickerControllerDelegate>
// 完成视频录制,并压缩后显示大小、时长
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// 拿到视频地址
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
// 将视频第一帧图片赋值给按钮
[self.addVedioBtn setImage:[self getFirstFrameWithVideoURL:sourceURL] forState:UIControlStateNormal];
CGFloat videoSize = [self getFileSize:[sourceURL path]];
NSLog(@"压缩处理之前的视频时长:%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
NSLog(@"压缩处理之前的视频大小:%@", [NSString stringWithFormat:@"%.2f MB", videoSize]);
// 预设压缩质量(最高画质)
_qualityPreset = AVAssetExportPresetHighestQuality;
// 如果视频大于 1000MB 则最低画质压缩
if (videoSize > 1000) {
_qualityPreset = AVAssetExportPresetLowQuality;
} else if (videoSize > 20) {
// 中等画质压缩
_qualityPreset = AVAssetExportPresetMediumQuality;
}
// 配置输出的视频文件,保存在app自己的沙盒路径里,在上传后删除掉。
NSURL *newVideoUrl;
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;
[picker dismissViewControllerAnimated:YES completion:nil];
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}
// 视频压缩转码处理
- (void)convertVideoQuailtyWithInputURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
completeHandler:(void (^)(AVAssetExportSession*))handler {
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
if (!_qualityPreset) {
_qualityPreset = AVAssetExportPresetMediumQuality;
}
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:_qualityPreset];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled:
NSLog(@"AVAssetExportSessionStatusCancelled");
break;
case AVAssetExportSessionStatusUnknown:
NSLog(@"AVAssetExportSessionStatusUnknown");
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"AVAssetExportSessionStatusWaiting");
break;
case AVAssetExportSessionStatusExporting:
NSLog(@"AVAssetExportSessionStatusExporting");
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"AVAssetExportSessionStatusCompleted");
CGFloat videoSize = [self getFileSize:[outputURL path]];
NSLog(@"压缩处理后的视频时长:%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
NSLog(@"压缩处理后的视频大小:%@", [NSString stringWithFormat:@"%.2f MB", videoSize]);
// 导出完成后再赋值
_videoPath = [outputURL path];
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
#pragma mark *** Video Handling -------------- End -------------- ***