iOS 視訊 轉碼MP4 /視訊裁剪 /上傳

weixin_34007020發表於2017-11-03

///////////////////////////////

//視訊轉碼方法    傳相簿或者相機得到的url和給視訊命名

-(void)shipinZhuanma:(NSURL *)url withName:(NSString *)name{

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

[SVProgressHUD showWithStatus:@"處理中..."];

[self creatSandBoxFilePathIfNoExist];

//儲存至沙盒路徑

NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *videoPath = [NSString stringWithFormat:@"%@/zhuanMaVideo", pathDocuments];

NSString *sandboxPath = [videoPath stringByAppendingPathComponent:name];

//轉碼配置

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];

//AVAssetExportPresetMediumQuality可以更改,是列舉型別,官方有提供,更改該值可以改變視訊的壓縮比例

AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];

exportSession.shouldOptimizeForNetworkUse = YES;

exportSession.outputURL = [NSURL fileURLWithPath:sandboxPath];

//AVFileTypeMPEG4 檔案輸出型別,可以更改,是列舉型別,官方有提供,更改該值也可以改變視訊的壓縮比例

exportSession.outputFileType = AVFileTypeMPEG4;

[exportSession exportAsynchronouslyWithCompletionHandler:^{

int exportStatus = exportSession.status;

NSLog(@"%d",exportStatus);

switch (exportStatus)

{

case AVAssetExportSessionStatusFailed:

{

// log error to text view

NSError *exportError = exportSession.error;

NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);

//轉碼失敗

break;

}

case AVAssetExportSessionStatusCompleted:

{

[SVProgressHUD dismiss];

NSData *data = [NSData dataWithContentsOfFile:sandboxPath];

if (data) {

NSString *videoDataString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

//把視訊二進位制流 寫入沙盒

NSString*docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;

//字典寫檔案--> ~/Documents/字典

NSDictionary*dic = @{@"shipinName":name,@"shipinDate":videoDataString};

//拼出檔案地址

NSString*dicPath = [docPath stringByAppendingPathComponent:@"飛行圈視訊字典"];

//寫入檔案

[dic writeToFile:dicPath atomically:YES];

}

}

}

}];

}

- (void)creatSandBoxFilePathIfNoExist

{

//沙盒路徑

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDirectory = [paths objectAtIndex:0];

NSLog(@"databse--->%@",documentDirectory);

NSFileManager *fileManager = [[NSFileManager alloc] init];

NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

//建立目錄

NSString *createPath = [NSString stringWithFormat:@"%@/zhuanMaVideo", pathDocuments];

// 判斷資料夾是否存在,如果不存在,則建立

if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {

[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];

} else {

NSLog(@"FileImage is exists.");

}

}

//上傳視訊資料方法

- (void)videoGO_FuwuQI{

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

[SVProgressHUD showWithStatus:@" "];

//    __weak typeof(self) weakSelf = self;

NSString*docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;

NSString*dicPath = [docPath stringByAppendingPathComponent:@"飛行圈視訊字典"];

//讀出檔案內容

NSDictionary*readDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];

//////這是視訊上傳伺服器的地址  

//    NSString *svr = [NSString stringWithFormat:@"%@JieKou/Shipinku_Jiekou/shipingupload.aspx",glaFly_upIMG];

NSString *svr = [NSString stringWithFormat:@"%@%@",glaFly_upIMG,self.shangURL];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.requestSerializer = [AFJSONRequestSerializer serializer];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"image/png",nil];

//////這是視訊上傳伺服器的約好的鍵值

NSDictionary *parameters =@{@"videoname":readDic[@"shipinName"],@"videodata":readDic[@"shipinDate"]};

//    NSURLSessionDataTask *abc =

[manager POST:svr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {

//        dispatch_async(dispatch_get_main_queue(), ^{

//            [weakSelf.jinDuTiao setProgress:1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount animated:YES];

//            weakSelf.jiduLab.text = [NSString stringWithFormat:@"%.2f%",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount * 100];

//        });

} success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {

//        NSLog(@"上傳成功");

[SVProgressHUD dismiss];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

[SVProgressHUD dismiss];

NSLog(@"視訊上傳出錯:%@",error);

}];


}

-(void)shipinCaiJian:(NSURL *)url withName:(NSString *)name start:(CGFloat)startTime end:(CGFloat)endTime{

[self cropWithVideoUrlStr:url withName:name start:startTime end:endTime completion:^(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess) {

}];

}

 ///////////////////////////////視訊擷取 

- (void)cropWithVideoUrlStr:(NSURL *)videoUrl withName:(NSString *)name start:(CGFloat)startTime end:(CGFloat)endTime completion:(void (^)(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess))completionHandle

{

[self creatSandBoxFilePathIfNoExist];

//儲存至沙盒路徑

NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *videoPath = [NSString stringWithFormat:@"%@/zhuanMaVideo", pathDocuments];

NSString *sandboxPath = [videoPath stringByAppendingPathComponent:name];

//轉碼配置

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoUrl options:nil];

//AVAssetExportPresetMediumQuality可以更改,是列舉型別,官方有提供,更改該值可以改變視訊的壓縮比例

AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];

exportSession.shouldOptimizeForNetworkUse = YES;

exportSession.outputURL = [NSURL fileURLWithPath:sandboxPath];

//AVFileTypeMPEG4 檔案輸出型別,可以更改,是列舉型別,官方有提供,更改該值也可以改變視訊的壓縮比例

exportSession.outputFileType = AVFileTypeMPEG4;

/////////////////////////////////////////////////

///////////////////////////////-------華麗的分割線-------////////////////////////////////////////////////

/////////////////////////////////////////////////

CMTime start = CMTimeMakeWithSeconds(startTime, asset.duration.timescale);

CMTime duration = CMTimeMakeWithSeconds(endTime - startTime,asset.duration.timescale);

CMTimeRange range = CMTimeRangeMake(start, duration);

exportSession.timeRange = range;

[exportSession exportAsynchronouslyWithCompletionHandler:^{

[SVProgressHUD dismiss];

switch ([exportSession status]) {

case AVAssetExportSessionStatusFailed:

{

NSLog(@"合成失敗:%@", [[exportSession error] description]);

completionHandle(exportSession.outputURL, endTime, NO);

}

break;

case AVAssetExportSessionStatusCancelled:

{

completionHandle(exportSession.outputURL, endTime, NO);

}

break;

case AVAssetExportSessionStatusCompleted:

{

completionHandle(exportSession.outputURL, endTime, YES);

NSData *data = [NSData dataWithContentsOfFile:sandboxPath];

if (data) {

NSString *videoDataString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

//把視訊二進位制流 寫入沙盒

NSString*docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;

//字典寫檔案--> ~/Documents/字典

NSDictionary*dic = @{@"shipinName":name,@"shipinDate":videoDataString};

//拼出檔案地址

NSString*dicPath = [docPath stringByAppendingPathComponent:@"飛行圈視訊字典"];

//寫入檔案

[dic writeToFile:dicPath atomically:YES];

}

}

break;

default:

{

completionHandle(exportSession.outputURL, endTime, NO);

} break;

}

}];

}

@end

相關文章