參考 Unclefeng iOS視頻壓縮處理html
AVAssetExportSession屬於<AVFoundation/AVFoundation.h> 這個類, 官方API 是這樣解釋說明的, AVAssetExportSession 是對AVAsset對象內容進行轉碼, 並輸出到制定的路徑;ide
- AVAssetExportPresetLowQuality - AVAssetExportPresetMediumQuality - AVAssetExportPresetHighestQualitAy - AVAssetExportPreset640x480 - AVAssetExportPreset1280x720
outputURL , 爲輸出內容的URL, (指定一個文件路徑, 而後根據路徑初始化一個URL, 賦給, outputURL) outputFileType, 爲輸出壓縮後視頻內容的格式類型url
// Created by iOS-Developer on 16/2/19. // Copyright © 2016年 iOS-Jessonliu. All rights reserved. // #import "JFCompressionVideo.h" #import <AVFoundation/AVFoundation.h> #define CompressionVideoPaht [NSHomeDirectory() stringByAppendingFormat:@"/Documents/CompressionVideoField"] @interface JFCompressionVideo () @end @implementation JFCompressionVideo + (void)compressedVideoOtherMethodWithURL:(NSURL *)url compressionType:(NSString *)compressionType compressionResultPath:(CompressionSuccessBlock)resultPathBlock { NSString *resultPath; NSData *data = [NSData dataWithContentsOfURL:url]; CGFloat totalSize = (float)data.length / 1024 / 1024; AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset]; // 所支持的壓縮格式中是否有 所選的壓縮格式 if ([compatiblePresets containsObject:compressionType]) { // 用時間, 給文件從新命名, 防止視頻存儲覆蓋, NSDateFormatter *formater = [[NSDateFormatter alloc] init]; [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"]; NSFileManager *manager = [NSFileManager defaultManager]; BOOL isExists = [manager fileExistsAtPath:CompressionVideoPaht]; if (!isExists) { [manager createDirectoryAtPath:CompressionVideoPaht withIntermediateDirectories:YES attributes:nil error:nil]; } resultPath = [CompressionVideoPaht stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mov", [formater stringFromDate:[NSDate date]]]]; NSLog(@"resultPath = %@",resultPath); AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:compressionType]; exportSession.outputURL = [NSURL fileURLWithPath:resultPath]; exportSession.outputFileType = AVFileTypeMPEG4; exportSession.shouldOptimizeForNetworkUse = YES; [exportSession exportAsynchronouslyWithCompletionHandler:^(void) { if (exportSession.status == AVAssetExportSessionStatusCompleted) { NSData *data = [NSData dataWithContentsOfFile:resultPath]; float memorySize = (float)data.length / 1024 / 1024; NSLog(@"視頻壓縮後大小 %f", memorySize); resultPathBlock (resultPath, memorySize); } else { NSLog(@"壓縮失敗"); } }]; } else { NSLog(@"不支持 %@ 格式的壓縮", compressionType); } } /** * 清楚沙盒文件中, 壓縮後的視頻全部, 在使用過壓縮文件後, 不進行再次使用時, 可調用該方法, 進行刪除 */ + (void)removeCompressedVideoFromDocuments { NSFileManager *manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:CompressionVideoPaht]) { [[NSFileManager defaultManager] removeItemAtPath:CompressionVideoPaht error:nil]; } } @end