最近一直都是在做即時通訊APP相關(guān)的東西,一般在即時通訊中都會有發(fā)送視頻的功能。發(fā)送視頻的基本流程都是先上傳視頻文件,然后把視頻文件的URL放在消息體中發(fā)送出去赠制,通過傳輸層協(xié)議TCP或UDP。其中免不了要對視頻文件進(jìn)行轉(zhuǎn)碼壓縮挟憔,因?yàn)閷τ谀欠N幾分鐘左右的高清視頻钟些,動不動幾百M(fèi)的大小,實(shí)在是影響APP的性能和用戶體驗(yàn)绊谭。我在下面代碼中封裝了一個同步的視頻轉(zhuǎn)碼壓縮接口:
- (BOOL)compressVideoWithAsset:(AVURLAsset *)asset outputPath:(NSString *)outputPath {
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
// 轉(zhuǎn)碼配置政恍,建議選擇AVAssetExportPresetMediumQuality
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
exportSession.shouldOptimizeForNetworkUse = YES;
// 設(shè)置視頻轉(zhuǎn)碼輸出路徑
exportSession.outputURL = [NSURL fileURLWithPath:outputPath];
// 文件輸出類型,更改該值也可以改變視頻的壓縮比例
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
dispatch_group_leave(group);
}];
// 等待轉(zhuǎn)碼結(jié)果
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
AVAssetExportSessionStatus exportStatus = exportSession.status;
// 轉(zhuǎn)碼成功
if (exportStatus == AVAssetExportSessionStatusCompleted) {
return YES;
} else {
return NO;
}
}
可以采取如下的調(diào)用方式:
NSString *videoPath = [NSString stringWithFormat:@"%@/%lld.mp4", NSTemporaryDirectory(), (long long)([[NSDate date] timeIntervalSince1970] * 1000)];
BOOL compressResult = [self compressVideoWithAsset:urlAsset outputPath:videoPath];
// 壓縮成功
if (compressResult) {
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath] options:(NSDataReadingMappedIfSafe) error:NULL];
}
上面的視頻轉(zhuǎn)碼方案采用是系統(tǒng)提供的API达传,有條件的可以自己研發(fā)一套轉(zhuǎn)碼方案篙耗。希望本文可以幫助大家。