iOS拍攝視頻,壓縮并上傳服務器

從本地選擇視頻,或者用UIImagePickerController錄制視頻

小編也是第一次做視頻上傳,參考
http://blog.csdn.net/personsky/article/details/52471354實現的

//選擇本地視頻
- (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
    ipc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    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;//設置委托
 //在錄制視頻的界面添加點東西
    UIView *BgView = [[UIView alloc] init];
    BgView.LYW_X = LYWScreenWidth*0.5 - 150*X6Scale;
    BgView.LYW_Y = 40*Y6Scale;
    BgView.LYW_W = 300*X6Scale;
    BgView.LYW_H = 200*Y6Scale;
    
    UILabel *lab = [[UILabel alloc] init];
    lab.LYW_X = 0;
    lab.LYW_Y = 0;
    lab.LYW_W = 300*X6Scale;
    lab.LYW_H = 200*Y6Scale;
    lab.text = @“http://www.lxweimin.com/u/0158007b8d17”;
    lab.numberOfLines = 0;
    lab.textColor = [UIColor orangeColor];
    [BgView addSubview:lab];
    
    ipc.cameraOverlayView = BgView;

}

視頻錄制完成,保存到相冊


//完成視頻錄制,并壓縮后顯示大小、時長
- (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自己的沙盒路徑里,后面可以選擇是否在上傳后刪除掉。我建議刪除掉,免得占空間。
    _fileName = [NSString stringWithFormat:@"output-%@.mp4", [formater stringFromDate:[NSDate date]]];
    
    NSURL * url = [info objectForKey:UIImagePickerControllerMediaURL];
    NSString * urlStr = [url path];
    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
        //保存視頻到相簿,注意也可以使用ALAssetsLibrary來保存
        UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    }
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}


#pragma mark - 自定義方法
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        NSLog(@"保存視頻過程中發生錯誤,錯誤信息:%@",error.localizedDescription);
    } else {
        NSLog(@"視頻保存成功");
        _videoUrl = videoPath;
        NSURL * url = [NSURL fileURLWithPath:videoPath];
    
       //  self.dateTimeLab.text = [LYWRegex getCurrentTimes];
        //獲取視頻第一幀
        // [self.showBtn setBackgroundImage:[LYWRegex thumbnailImageForVideo:url atTime:1] forState:UIControlStateNormal];
        
    }
}

壓縮視頻并上傳給服務器 使用AFN



#pragma mark - 壓縮視頻
- (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);//這個是保存到手機相冊
                 _outputURL = outputURL;
                 //                 [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];
    }
}

#pragma mark - 上傳視頻
-(void)uploadVideo:(NSURL*)URL{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    NSData *data = [NSData dataWithContentsOfURL:URL];
    
    dict[@"loanvideo"] = data;
    dict[@"record_id"] = self.loan_record_id;
    
    NSString *uploadVideoUrl = [NSString stringWithFormat:@"%@%@",BaseUrl,@"uploadloanvideo"];
    
    [[NetworkHelper shareInstance] Post:uploadVideoUrl parameter:dict data:data name:@"loanvideo" fileName:_fileName mimeType:@"video/mpeg" success:^(id responseObject) {
        NSLog(@"視頻上傳成功");
 
        
    } failure:^(NSError *error) {
        NSLog(@"視頻上傳失敗");
    }];
    
}

Demo把視頻上傳到服務器的代碼注釋掉了
https://gitee.com/lanyingwei/codes/y6f4xrpdqwu35ln8st19z29

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容