iOS開發中向服務器上傳視頻的實踐

在最近的項目中,涉及到視頻上傳,在網上找了下資料,這裏整理下來希望對大家有幫助,這裏簡短談下整個流程;

1. 創建保存該視頻的文件夾

- (void)createVideoFolderIfNotExist
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    NSString *folderPath = [path stringByAppendingPathComponent:videoFolders];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isDirExist = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
    
    if(!(isDirExist && isDir))
    {
        BOOL create = [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!create){
            NSLog(@"創建保存視頻文件夾失敗");
        }
    }
}

2. 視頻錄製完以後保存的視頻

- (NSString *)getVideoSaveFilePathString
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    path = [path stringByAppendingPathComponent:videoFolders];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    
    NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@".mov"];
   
    return fileName;
}

3. 根據以上兩個方法

//最後合成爲 mp4
- (NSString *)getVideoMergeFilePathString
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    path = [path stringByAppendingPathComponent:videoFolders];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    
    NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@"merge.mp4"];
    
    return fileName;
}

#主要的代碼

 
    //根據設備輸出獲得連接
    AVCaptureConnection *captureConnection=[self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    
    //根據連接取得設備輸出的數據
    if (![self.captureMovieFileOutput isRecording]) {
//        shootBt.backgroundColor = UIColorFromRGB(0xfa5f66);
        //預覽圖層和視頻方向保持一致
        captureConnection.videoOrientation=[self.captureVideoPreviewLayer connection].videoOrientation;
        [self.captureMovieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:[self getVideoSaveFilePathString]] recordingDelegate:self];

 

#視頻壓縮

 

 NSString *path = [self getVideoMergeFilePathString];
    NSURL *mergeFileURL = [NSURL fileURLWithPath:path];
    
    AVMutableVideoCompositionInstruction *mainInstruciton = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    mainInstruciton.timeRange = CMTimeRangeMake(kCMTimeZero, totalDuration);
    mainInstruciton.layerInstructions = layerInstructionArray;
    AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
    mainCompositionInst.instructions = @[mainInstruciton];
    mainCompositionInst.frameDuration = CMTimeMake(1, 100);
    mainCompositionInst.renderSize = CGSizeMake(renderW, renderW*preLayerHWRate);
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
    exporter.videoComposition = mainCompositionInst;
    exporter.outputURL = mergeFileURL;
    exporter.outputFileType = AVFileTypeMPEG4; //mp4
    exporter.shouldOptimizeForNetworkUse = YES;
 
    
    [exporter exportAsynchronouslyWithCompletionHandler:^{

        if ([exporter status] == AVAssetExportSessionStatusCompleted) {
            dispatch_async(dispatch_get_main_queue(), ^{
           

#################  這裏的二進制就是上傳的東西了##################               
                NSData *data = [NSData dataWithContentsOfURL:exporter.outputURL];
              
    }];

########### 上傳的方法

    NSString *imageStr = @"公司接口";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
 
    [manager POST:imageStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            /*
           此方法參數
           1. 要上傳的[二進制數據]
           2. 對應網站上[upload.php中]處理文件的[字段"file"]
           3. 要保存在服務器上的[文件名]
           4. 上傳文件的[mimeType]
            */
        
        [formData appendPartWithFileData:datas name:@"video" fileName:@"videosNames" mimeType:@"video/mp4"];
//        [formData appendPartWithFormData:datas name:@"video"];
        
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
            
            
         NSDictionary *cashDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
 
            NSLog(@"%@",cashDic[@"remark"]);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"faile ----->%@",error);
            
        }];

.........................................................

 

#由於設計到公司服務器接口,下面代碼就不一一複製了。
 

發佈了48 篇原創文章 · 獲贊 54 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章