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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章