iOS录制(或选择)视频,压缩、上传(整理)

最新做的一个功能涉及到了视频的录制、压缩及上传。根据网上诸多大神的经验,终于算是调通了,但也发现了一些问题,所以把我的经验分享一下。

首先,肯定是调用一下系统的相机或相册


代码很基本:


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //选择本地视频  
  2. - (void)choosevideo  
  3. {  
  4.     UIImagePickerController *ipc = [[UIImagePickerController alloc] init];  
  5.     ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera,photoLibrary和photoAlbum  
  6.     NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"  
  7.     ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie  
  8.     [self presentViewController:ipc animated:YES completion:nil];  
  9.     ipc.delegate = self;//设置委托  
  10.       
  11. }  
  12.   
  13. //录制视频  
  14. - (void)startvideo  
  15. {  
  16.     UIImagePickerController *ipc = [[UIImagePickerController alloc] init];  
  17.     ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera,photoLibrary和photoAlbum  
  18.     NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"  
  19.     ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie  
  20.     [self presentViewController:ipc animated:YES completion:nil];  
  21.     ipc.videoMaximumDuration = 30.0f;//30秒  
  22.     ipc.delegate = self;//设置委托  
  23.       
  24. }  


iOS录制的视频格式是mov的,在Android和Pc上都不太好支持,所以要转换为MP4格式的,而且压缩一下,毕竟我们上传的都是小视频,不用特别清楚


为了反馈的清楚,先放两个小代码来获取视频的时长和大小,也是在网上找的,稍微改了一下。



[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (CGFloat) getFileSize:(NSString *)path  
  2. {  
  3.     NSLog(@"%@",path);  
  4.     NSFileManager *fileManager = [NSFileManager defaultManager];  
  5.     float filesize = -1.0;  
  6.     if ([fileManager fileExistsAtPath:path]) {  
  7.         NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性  
  8.         unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];  
  9.         filesize = 1.0*size/1024;  
  10.     }else{  
  11.         NSLog(@"找不到文件");  
  12.     }  
  13.     return filesize;  
  14. }//此方法可以获取文件的大小,返回的是单位是KB。  
  15. - (CGFloat) getVideoLength:(NSURL *)URL  
  16. {  
  17.       
  18.     AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];  
  19.     CMTime time = [avUrl duration];  
  20.     int second = ceil(time.value/time.timescale);  
  21.     return second;  
  22. }//此方法可以获取视频文件的时长。  




接收并压缩

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //完成视频录制,并压缩后显示大小、时长  
  2. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info  
  3. {  
  4.     NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];  
  5.     NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);  
  6.     NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);  
  7.     NSURL *newVideoUrl ; //一般.mp4  
  8.     NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可  
  9.     [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];  
  10.     newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里,后面可以选择是否在上传后删除掉。我建议删除掉,免得占空间。  
  11.     [picker dismissViewControllerAnimated:YES completion:nil];  
  12.     [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];  
  13. }  
  14. - (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL  
  15.                                outputURL:(NSURL*)outputURL  
  16.                          completeHandler:(void (^)(AVAssetExportSession*))handler  
  17. {  
  18.     AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];  
  19.       
  20.         AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];  
  21.         //  NSLog(resultPath);  
  22.         exportSession.outputURL = outputURL;  
  23.         exportSession.outputFileType = AVFileTypeMPEG4;  
  24.         exportSession.shouldOptimizeForNetworkUseYES;  
  25.         [exportSession exportAsynchronouslyWithCompletionHandler:^(void)  
  26.          {  
  27.              switch (exportSession.status) {  
  28.                  case AVAssetExportSessionStatusCancelled:  
  29.                      NSLog(@"AVAssetExportSessionStatusCancelled");  
  30.                      break;  
  31.                  case AVAssetExportSessionStatusUnknown:  
  32.                      NSLog(@"AVAssetExportSessionStatusUnknown");  
  33.                      break;  
  34.                  case AVAssetExportSessionStatusWaiting:  
  35.                      NSLog(@"AVAssetExportSessionStatusWaiting");  
  36.                      break;  
  37.                  case AVAssetExportSessionStatusExporting:  
  38.                      NSLog(@"AVAssetExportSessionStatusExporting");  
  39.                      break;  
  40.                  case AVAssetExportSessionStatusCompleted:  
  41.                      NSLog(@"AVAssetExportSessionStatusCompleted");  
  42.                      NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);  
  43.                      NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);  
  44.                        
  45.                      //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册  
  46.                        
  47.                      [self alertUploadVideo:outputURL];  
  48.                      break;  
  49.                  case AVAssetExportSessionStatusFailed:  
  50.                      NSLog(@"AVAssetExportSessionStatusFailed");  
  51.                      break;  
  52.              }  
  53.                
  54.          }];  
  55.       
  56. }  


我这里用了一个提醒,因为我的服务器比较弱,不能传太大的文件


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)alertUploadVideo:(NSURL*)URL{  
  2.     CGFloat size = [self getFileSize:[URL path]];  
  3.     NSString *message;  
  4.     NSString *sizeString;  
  5.     CGFloat sizemb= size/1024;  
  6.     if(size<=1024){  
  7.         sizeString = [NSString stringWithFormat:@"%.2fKB",size];  
  8.     }else{  
  9.         sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];  
  10.     }  
  11.       
  12.       
  13.       
  14.       
  15.     if(sizemb<2){  
  16.         [self uploadVideo:URL];  
  17.     }  
  18.       
  19.     else if(sizemb<=5){  
  20.         message = [NSString stringWithFormat:@"视频%@,大于2MB会有点慢,确定上传吗?", sizeString];  
  21.         UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil  
  22.                                                                                   message: message  
  23.                                                                            preferredStyle:UIAlertControllerStyleAlert];  
  24.           
  25.           
  26.         [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {  
  27.             [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];  
  28.             [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除,以免占用手机硬盘空间(沙盒)  
  29.               
  30.         }]];  
  31.         [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {  
  32.               
  33.               
  34.             [self uploadVideo:URL];  
  35.               
  36.               
  37.               
  38.               
  39.         }]];  
  40.         [self presentViewController:alertController animated:YES completion:nil];  
  41.   
  42.           
  43.     }else if(sizemb>5){  
  44.         message = [NSString stringWithFormat:@"视频%@,超过5MB,不能上传,抱歉。", sizeString];  
  45.         UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil  
  46.                                                                                   message: message  
  47.                                                                            preferredStyle:UIAlertControllerStyleAlert];  
  48.           
  49.         [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {  
  50.             [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];  
  51.             [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除,以免占用手机硬盘空间  
  52.               
  53.         }]];  
  54.         [self presentViewController:alertController animated:YES completion:nil];  
  55.   
  56.     }  
  57.       
  58.       
  59. }  


最后上上传的代码,这个是根据服务器来的,而且还是用的MKNetworking,据说已经过时了,放上来大家参考一下吧,AFNet也差不多,就是把NSData传上去。


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)uploadVideo:(NSURL*)URL{  
  2.     //[MyTools showTipsWithNoDisappear:nil message:@"正在上传..."];  
  3.     NSData *data = [NSData dataWithContentsOfURL:URL];  
  4.     MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"www.ylhuakai.com" customHeaderFields:nil];  
  5.     NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];  
  6.     NSString *updateURL;  
  7.     updateURL = @"/alflower/Data/sendupdate";  
  8.       
  9.       
  10.     [dic setValue:[NSString stringWithFormat:@"%@",User_id] forKey:@"openid"];  
  11.     [dic setValue:[NSString stringWithFormat:@"%@",[self.web objectForKey:@"web_id"]] forKey:@"web_id"];  
  12.     [dic setValue:[NSString stringWithFormat:@"%i",insertnumber] forKey:@"number"];  
  13.     [dic setValue:[NSString stringWithFormat:@"%i",insertType] forKey:@"type"];  
  14.       
  15.     MKNetworkOperation *op = [engine operationWithPath:updateURL params:dic httpMethod:@"POST"];  
  16.     [op addData:data forKey:@"video" mimeType:@"video/mpeg" fileName:@"aa.mp4"];  
  17.     [op addCompletionHandler:^(MKNetworkOperation *operation) {  
  18.         NSLog(@"[operation responseData]-->>%@", [operation responseString]);  
  19.         NSData *data = [operation responseData];  
  20.         NSDictionary *resweiboDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];  
  21.         NSString *status = [[resweiboDict objectForKey:@"status"]stringValue];  
  22.         NSLog(@"addfriendlist status is %@", status);  
  23.         NSString *info = [resweiboDict objectForKey:@"info"];  
  24.         NSLog(@"addfriendlist info is %@", info);  
  25.        // [MyTools showTipsWithView:nil message:info];  
  26.         // [SVProgressHUD showErrorWithStatus:info];  
  27.         if ([status isEqualToString:@"1"])  
  28.         {  
  29.             [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];  
  30.             [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//上传之后就删除,以免占用手机硬盘空间;  
  31.               
  32.         }else  
  33.         {  
  34.             //[SVProgressHUD showErrorWithStatus:dic[@"info"]];  
  35.         }  
  36.         // [[NSNotificationCenter defaultCenter] postNotificationName:@"StoryData" object:nil userInfo:nil];  
  37.           
  38.           
  39.     }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {  
  40.         NSLog(@"MKNetwork request error : %@", [err localizedDescription]);  
  41.     }];  
  42.     [engine enqueueOperation:op];  
  43.   
  44.   
  45. }  
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值