iOS视频录制(或选择)压缩及上传功能(整理)

 更新时间:2017年03月23日 15:29:03   作者:VKOOY  
最新做的一个功能涉及到了视频的录制、压缩及上传功能,经过大神的一番教导,终于倒腾清楚了,今天小编把问题经过记录一下分享到脚本之家平台,供大家参考

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

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

代码很基本:

//选择本地视频 
- (void)choosevideo 
{ 
 UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; 
 ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera,photoLibrary和photoAlbum 
 NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie" 
 ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie 
 [self presentViewController:ipc animated:YES completion:nil]; 
 ipc.delegate = self;//设置委托 
} 
//录制视频 
- (void)startvideo 
{ 
 UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; 
 ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera,photoLibrary和photoAlbum 
 NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie" 
 ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie 
 [self presentViewController:ipc animated:YES completion:nil]; 
 ipc.videoMaximumDuration = 30.0f;//30秒 
 ipc.delegate = self;//设置委托 
} 

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

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

- (CGFloat) getFileSize:(NSString *)path 
{ 
 NSLog(@"%@",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; 
 }else{ 
  NSLog(@"找不到文件"); 
 } 
 return filesize; 
}//此方法可以获取文件的大小,返回的是单位是KB。 
- (CGFloat) getVideoLength:(NSURL *)URL 
{ 
 AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL]; 
 CMTime time = [avUrl duration]; 
 int second = ceil(time.value/time.timescale); 
 return second; 
}//此方法可以获取视频文件的时长。

 接收并压缩

//完成视频录制,并压缩后显示大小、时长 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
 NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL]; 
 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]); 
 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]); 
 NSURL *newVideoUrl ; //一般.mp4 
 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]]]] ;//这个是保存在app自己的沙盒路径里,后面可以选择是否在上传后删除掉。我建议删除掉,免得占空间。 
 [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]; 
  AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality]; 
  // NSLog(resultPath); 
  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"); 
      NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]); 
      NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]); 
      //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册 
      [self alertUploadVideo:outputURL]; 
      break; 
     case AVAssetExportSessionStatusFailed: 
      NSLog(@"AVAssetExportSessionStatusFailed"); 
      break; 
    } 
   }]; 
} 

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

-(void)alertUploadVideo:(NSURL*)URL{ 
 CGFloat size = [self getFileSize:[URL path]]; 
 NSString *message; 
 NSString *sizeString; 
 CGFloat sizemb= size/1024; 
 if(size<=1024){ 
  sizeString = [NSString stringWithFormat:@"%.2fKB",size]; 
 }else{ 
  sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb]; 
 } 
 if(sizemb<2){ 
  [self uploadVideo:URL]; 
 } 
 else if(sizemb<=5){ 
  message = [NSString stringWithFormat:@"视频%@,大于2MB会有点慢,确定上传吗?", sizeString]; 
  UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil 
                     message: message 
                   preferredStyle:UIAlertControllerStyleAlert]; 
  [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { 
   [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil]; 
   [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除,以免占用手机硬盘空间(沙盒) 
  }]]; 
  [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { 
   [self uploadVideo:URL]; 
  }]]; 
  [self presentViewController:alertController animated:YES completion:nil]; 
 }else if(sizemb>5){ 
  message = [NSString stringWithFormat:@"视频%@,超过5MB,不能上传,抱歉。", sizeString]; 
  UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil 
                     message: message 
                   preferredStyle:UIAlertControllerStyleAlert]; 
  [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { 
   [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil]; 
   [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除,以免占用手机硬盘空间 
  }]]; 
  [self presentViewController:alertController animated:YES completion:nil]; 
 } 
} 

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

-(void)uploadVideo:(NSURL*)URL{ 
 //[MyTools showTipsWithNoDisappear:nil message:@"正在上传..."]; 
 NSData *data = [NSData dataWithContentsOfURL:URL]; 
 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"www.ylhuakai.com" customHeaderFields:nil]; 
 NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; 
 NSString *updateURL; 
 updateURL = @"/alflower/Data/sendupdate"; 
 [dic setValue:[NSString stringWithFormat:@"%@",User_id] forKey:@"openid"]; 
 [dic setValue:[NSString stringWithFormat:@"%@",[self.web objectForKey:@"web_id"]] forKey:@"web_id"]; 
 [dic setValue:[NSString stringWithFormat:@"%i",insertnumber] forKey:@"number"]; 
 [dic setValue:[NSString stringWithFormat:@"%i",insertType] forKey:@"type"]; 
 MKNetworkOperation *op = [engine operationWithPath:updateURL params:dic httpMethod:@"POST"]; 
 [op addData:data forKey:@"video" mimeType:@"video/mpeg" fileName:@"aa.mp4"]; 
 [op addCompletionHandler:^(MKNetworkOperation *operation) { 
  NSLog(@"[operation responseData]-->>%@", [operation responseString]); 
  NSData *data = [operation responseData]; 
  NSDictionary *resweiboDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 
  NSString *status = [[resweiboDict objectForKey:@"status"]stringValue]; 
  NSLog(@"addfriendlist status is %@", status); 
  NSString *info = [resweiboDict objectForKey:@"info"]; 
  NSLog(@"addfriendlist info is %@", info); 
  // [MyTools showTipsWithView:nil message:info]; 
  // [SVProgressHUD showErrorWithStatus:info]; 
  if ([status isEqualToString:@"1"]) 
  { 
   [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil]; 
   [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//上传之后就删除,以免占用手机硬盘空间; 
  }else 
  { 
   //[SVProgressHUD showErrorWithStatus:dic[@"info"]]; 
  } 
  // [[NSNotificationCenter defaultCenter] postNotificationName:@"StoryData" object:nil userInfo:nil]; 
 }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) { 
  NSLog(@"MKNetwork request error : %@", [err localizedDescription]); 
 }]; 
 [engine enqueueOperation:op]; 
} 

以上所述是小编给大家介绍的iOS视频录制(或选择)压缩及上传功能(整理),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • iOS中tableview实现编辑、全选及删除等功能的方法示例

    iOS中tableview实现编辑、全选及删除等功能的方法示例

    这篇文章主要给大家介绍了关于iOS中tableview实现编辑、全选及删除等功能的相关资料,文中通过示例代码介绍的非常详细,不仅是介绍实现的方法,将实现过程中遇到的问题也都分享出来了,需要的朋友们下面来一起看看吧。
    2017-07-07
  • 学习iOS全局跑马灯

    学习iOS全局跑马灯

    这篇文章主要帮助大家学习iOS全局跑马灯,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • IOS中UIWebView的使用详解

    IOS中UIWebView的使用详解

    这篇文章主要介绍了IOS中UIWebView的使用详解,涉及到初始化与三种加载方式,一些常用的属性和变量及ios7中的一些新特征,本文介绍的非常详细,感兴趣的朋友一起学习吧
    2016-02-02
  • iOS UIAlertController中UITextField添加晃动效果与边框颜色详解

    iOS UIAlertController中UITextField添加晃动效果与边框颜色详解

    这篇文章主要给大家介绍了关于iOS UIAlertController中UITextField添加晃动效果与边框颜色的相关资料,实现后的效果非常适合在开发中使用,文中给出了详细的示例代码,需要的朋友可以参考借鉴,下面随着小编来一起看看吧。
    2017-10-10
  • 110.iOS10新特性适配教程XCode8新特性解析

    110.iOS10新特性适配教程XCode8新特性解析

    这篇文章主要介绍了110.iOS10新特性适配教程XCode8新特性解析的相关资料,需要的朋友可以参考下
    2016-10-10
  • iOS下Safari点击事件失效的解决方法

    iOS下Safari点击事件失效的解决方法

    这篇文章主要给大家介绍了关于在iOS下Safari点击事件失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2018-01-01
  • iOS中设置父视图透明但内容不透明的方法

    iOS中设置父视图透明但内容不透明的方法

    设置一定的背景透明会让用户的体验非常不错,下面这篇文章就主要跟大家分享了iOS中设置父视图透明但内容不透明的方法,文中给出了详细的示例代码,需要的朋友们下面来一起看看吧。
    2017-05-05
  • 详解Objective-C编程中对设计模式中适的配器模式的使用

    详解Objective-C编程中对设计模式中适的配器模式的使用

    这篇文章主要介绍了Objective-C编程中对设计模式中适的配器模式的使用,适配器模式中的Adapter适配器允许接口不兼容的类在一起工作,需要的朋友可以参考下
    2016-03-03
  • iOS UICollectionView刷新时闪屏的解决方法

    iOS UICollectionView刷新时闪屏的解决方法

    本篇文章主要介绍了iOS UICollectionView刷新时闪屏的解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • iOS如何让tableview支持不同种类的cell详解

    iOS如何让tableview支持不同种类的cell详解

    这篇文章主要给大家介绍了关于iOS如何让tableview支持不同种类的cell的相关资料,文中通过示例代码详细的给大家介绍了实现的两种方法,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-08-08

最新评论