iOS AVFoundation自定義視頻壓縮 自定義視頻 比特率 幀率 寬高等

最近做視頻壓縮上傳功能 剛開始用的蘋果已經簡單封裝好的 AVAssetExportSession 框架 視頻壓縮上傳後 發現有些視頻壓縮後 反而變大了
後來參考了近期視頻優化做的比較不錯的douyin 發現不論上傳多大的視頻 被douyin壓縮以後比特率(視頻每秒傳輸的大小 單位:比特率(bps) / 千比特率(kbps))基本都維持在1500 kbps左右 經測試 這是對視頻壓縮後 文件大小 影響最大的一個參數
另外 還有比如幀率 視頻寬高 等參數 也對視頻壓縮有一定的影響
用此方法 在項目中實測 基本可以滿足絕大多數需求
如果你僅僅是想完成需求 不想研究代碼的話
到這裏可以結束閱讀了
直接翻到最下面下載Demo 複製我封裝好的方法 調用 就行了
繼續往下看的話:
代碼用到了訪問相機 訪問相冊 訪問麥克風 添加視頻到相冊四個權限
使用前 先把info中相機相冊對應權限打開
info.plist 用Source Code方式打開的話 這樣寫:

1.  `<key>NSCameraUsageDescription</key>`
2.  `<string>是否允許訪問相機</string>`
3.  `<key>NSMicrophoneUsageDescription</key>`
4.  `<string>App需要您的同意才能訪問麥克風</string>`
5.  `<key>NSPhotoLibraryUsageDescription</key>`
6.  `<string>是否允許訪問相冊</string>`
7.  `<key>NSPhotoLibraryAddUsageDescription</key>`
8.  `<string>是否允許添加視頻或圖片到相冊</string>`

info.plist 用Property List方式打開的話 這樣配置:

配置好了 開始寫代碼:
ViewController.m
使用系統的UIImagePickerController選擇或者拍攝對應的視頻
使用前 先遵守<UIImagePickerControllerDelegate, UINavigationControllerDelegate>這倆協議
然後寫這個

1.  `@property  (nonatomic, strong)  UIImagePickerController  *imagePicker;`

從相冊中選擇視頻 代碼註釋寫的比較詳細了

1.  `//從相冊中選擇視頻`
2.  `-  (IBAction)chooseVideoBtnClick:(id)sender {`
3.  `if  ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])`
4.  `{`
5.  `self.imagePicker =  [[UIImagePickerController alloc] init];`
6.  `self.imagePicker.delegate  =  self;`
7.  `/*`
8.  `* 設置資源文件來源 圖庫 相機 相冊`
9.  `* UIImagePickerControllerSourceTypePhotoLibrary,`
10.  `* UIImagePickerControllerSourceTypeCamera,`
11.  `* UIImagePickerControllerSourceTypeSavedPhotosAlbum`
12.  `**/`
13.  `self.imagePicker.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;`
14.  `/*`
15.  `* 設置媒體類型`
16.  `* (NSString *)kUTTypeVideo 無聲視頻`
17.  `* (NSString *)kUTTypeMovie 有聲視頻`
18.  `* (NSString *)kUTTypeAudio 音頻`
19.  `* 等...`
20.  `**/`
21.  `[self.imagePicker setMediaTypes:@[(NSString  *)kUTTypeMovie]];`
22.  `self.imagePicker.videoQuality =  UIImagePickerControllerQualityTypeHigh;`
23.  `[self presentViewController:self.imagePicker animated:YES completion:nil];`

25.  `}else{`
26.  `[self showAlertViewWithTitle:@"相機不可用" message:@"" withCancelButtonTitle:@"知道了"];`
27.  `}`
28.  `}`

相機拍攝視頻

1.  `//拍攝視頻`
2.  `-  (IBAction)recordVideoBtnClick:(id)sender {`
3.  `if  ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])`
4.  `{`
5.  `self.imagePicker =  [[UIImagePickerController alloc] init];`
6.  `self.imagePicker.delegate  =  self;`
7.  `/*`
8.  `* 設置資源文件來源 圖庫 相機 相冊`
9.  `* UIImagePickerControllerSourceTypePhotoLibrary,`
10.  `* UIImagePickerControllerSourceTypeCamera,`
11.  `* UIImagePickerControllerSourceTypeSavedPhotosAlbum`
12.  `**/`
13.  `self.imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;`
14.  `/*`
15.  `* 設置媒體類型`
16.  `* (NSString *)kUTTypeVideo 無聲視頻`
17.  `* (NSString *)kUTTypeMovie 有聲視頻`
18.  `* (NSString *)kUTTypeAudio 音頻`
19.  `* 等...`
20.  `**/`
21.  `[self.imagePicker setMediaTypes:@[(NSString  *)kUTTypeMovie]];`
22.  `self.imagePicker.videoQuality =  UIImagePickerControllerQualityTypeHigh;`
23.  `[self presentViewController:self.imagePicker animated:YES completion:nil];`

25.  `}else{`
26.  `[self showAlertViewWithTitle:@"相機不可用" message:@"" withCancelButtonTitle:@"知道了"];`
27.  `}`
28.  `}`

取消選擇或者拍攝時的回調
UIImagePickerControllerDelegate

1.  `-(void)imagePickerControllerDidCancel:(UIImagePickerController  *)picker{`
2.  `[self.imagePicker dismissViewControllerAnimated:YES completion:nil];`
3.  `[self showAlertViewWithTitle:@"用戶取消操作" message:@"" withCancelButtonTitle:@"好的"];`

5.  `}`

視頻選擇 或者拍攝好以後回調

1.  `-(void)imagePickerController:(UIImagePickerController  *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id>  *)info{`
2.  `//獲取媒體類型`
3.  `NSString  *type =  [info objectForKey:UIImagePickerControllerMediaType];`
4.  `//媒體類型是視頻時`
5.  `if  ([type isEqualToString:@"public.movie"])`
6.  `{`
7.  `NSLog(@"===video URL = %@===",  [info objectForKey:UIImagePickerControllerMediaURL]);`
8.  `//視頻路徑URL`
9.  `NSURL *outputUrl =  [info objectForKey:UIImagePickerControllerMediaURL];`
10.  `//關閉相冊界面`
11.  `[picker dismissViewControllerAnimated:YES completion:^{`
12.  `//執行視頻壓縮功能` 
13.  `[self compressVideoWithVideoUrl:outputUrl];`
14.  `}];`
15.  `}`
16.  `}`

//壓縮視頻

1.  `/*`
2.  `* 自定義視頻壓縮`
3.  `* videoUrl 原視頻url路徑 必傳`
4.  `* outputBiteRate 壓縮視頻至指定比特率(bps) 可傳nil 默認1500kbps`
5.  `* outputFrameRate 壓縮視頻至指定幀率 可傳nil 默認30fps`
6.  `* outputWidth 壓縮視頻至指定寬度 可傳nil 默認960`
7.  `* outputWidth 壓縮視頻至指定高度 可傳nil 默認540`
8.  `* compressComplete 壓縮後的視頻信息回調 (id responseObjc) 可自行打印查看`
9.  `**/`
10.  `-  (void)compressVideoWithVideoUrl:(NSURL *)outputUrl{`
11.  `[VideoCompress compressVideoWithVideoUrl:outputUrl withBiteRate:@(1500  *  1024) withFrameRate:@(30) withVideoWidth:@(960) withVideoHeight:@(540) compressComplete:^(id responseObjc)  {`
12.  `NSString  *filePathStr =  [responseObjc objectForKey:@"urlStr"];`
13.  `AVURLAsset  *asset =  [AVURLAsset assetWithURL:[NSURL fileURLWithPath:filePathStr]];`
14.  `AVAssetTrack  *videoTrack =  [asset tracksWithMediaType:AVMediaTypeVideo].firstObject;`
15.  `//視頻大小 MB`
16.  `unsigned  long  long fileSize =  [[NSFileManager defaultManager] attributesOfItemAtPath:filePathStr error:nil].fileSize;`
17.  `float fileSizeMB = fileSize /  (1024.0*1024.0);`
18.  `//視頻寬高`
19.  `NSInteger videoWidth = videoTrack.naturalSize.width;`
20.  `NSInteger videoHeight = videoTrack.naturalSize.height;`
21.  `//比特率`
22.  `NSInteger kbps = videoTrack.estimatedDataRate /  1024;`
23.  `//幀率`
24.  `NSInteger frameRate =  [videoTrack nominalFrameRate];`
25.  `NSLog(@"\nfileSize after compress = %.2f MB,\n videoWidth = %ld,\n videoHeight = %ld,\n video bitRate = %ld\n, video frameRate = %ld", fileSizeMB, videoWidth, videoHeight, kbps, frameRate);`
26.  `//        NSData *videoData = [NSData dataWithContentsOfFile:filePathStr];`
27.  `//                    NSData *videoData = [NSData dataWithContentsOfURL:asset.URL];`
28.  `//在這裏上傳或者保存已經處理好的視頻文件`
29.  `//保存視頻至相冊`
30.  `UISaveVideoAtPathToSavedPhotosAlbum(filePathStr,  self,  @selector(videoSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),  nil);`
31.  `}];`
32.  `}`

取消事件的一些彈框

1.  `-  (void)showAlertViewWithTitle:(NSString*)title message:(NSString*)msg withCancelButtonTitle:(NSString  *)cancelButtonTitle{`
2.  `UIAlertController* alertController =  [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];`
3.  `[alertController addAction:[UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction  *  _Nonnull action)  {`
4.  `}]];`
5.  `[self presentViewController:alertController animated:YES completion:nil];`
6.  `}`

//視頻保存成功提示框

1.  `#pragma mark 保存視頻後的回調`
2.  `-  (void)videoSavedToPhotosAlbum:(NSString  *)videoUrlStr didFinishSavingWithError:(NSError*)error contextInfo:(id)contextInfo{`
3.  `NSString*message =@"提示";`
4.  `if(!error)  {`
5.  `message =  @"視頻成功保存到相冊";`
6.  `}else{`
7.  `message =  [error description];`
8.  `}`
9.  `[self showAlertViewWithTitle:@"提示" message:message withCancelButtonTitle:@"確定"];`
10.  `}`

VideoCompress.m

1.  `/*`
2.  `* 自定義視頻壓縮`
3.  `* videoUrl 原視頻url路徑 必傳`
4.  `* outputBiteRate 壓縮視頻至指定比特率(bps) 可傳nil 默認1500kbps`
5.  `* outputFrameRate 壓縮視頻至指定幀率 可傳nil 默認30fps`
6.  `* outputWidth 壓縮視頻至指定寬度 可傳nil 默認960`
7.  `* outputWidth 壓縮視頻至指定高度 可傳nil 默認540`
8.  `* compressComplete 壓縮後的視頻信息回調 (id responseObjc) 可自行打印查看`
9.  `**/`
10.  `+  (void)compressVideoWithVideoUrl:(NSURL *)videoUrl withBiteRate:(NSNumber  *  _Nullable)outputBiteRate withFrameRate:(NSNumber  *  _Nullable)outputFrameRate withVideoWidth:(NSNumber  *  _Nullable)outputWidth withVideoHeight:(NSNumber  *  _Nullable)outputHeight compressComplete:(void(^)(id responseObjc))compressComplete{`
11.  `if  (!videoUrl)  {`
12.  `[SVProgressHUD showErrorWithStatus:@"視頻路徑不能爲空"];`
13.  `return;`
14.  `}`
15.  `NSLog(@"===videoUrl.abs = %@, videoUrl.path = %@", videoUrl.absoluteString, videoUrl.path);`
16.  `NSInteger compressBiteRate = outputBiteRate ?  [outputBiteRate integerValue]  :  1500  *  1024;`
17.  `NSInteger compressFrameRate = outputFrameRate ?  [outputFrameRate integerValue]  :  30;`
18.  `NSInteger compressWidth = outputWidth ?  [outputWidth integerValue]  :  960;`
19.  `NSInteger compressHeight = outputHeight ?  [outputHeight integerValue]  :  540;`
20.  `//取出原視頻詳細資料`
21.  `AVURLAsset  *asset =  [AVURLAsset assetWithURL:videoUrl];`
22.  `//視頻時長 S`
23.  `CMTime time =  [asset duration];`
24.  `NSInteger seconds =  ceil(time.value/time.timescale);`
25.  `if  (seconds <  3)  {`
26.  `[SVProgressHUD showErrorWithStatus:@"請上傳3秒以上的視頻"];`
27.  `return;`
28.  `}`
29.  `//壓縮前原視頻大小MB`
30.  `unsigned  long  long fileSize =  [[NSFileManager defaultManager] attributesOfItemAtPath:videoUrl.path error:nil].fileSize;`
31.  `float fileSizeMB = fileSize /  (1024.0*1024.0);`
32.  `//取出asset中的視頻文件`
33.  `AVAssetTrack  *videoTrack =  [asset tracksWithMediaType:AVMediaTypeVideo].firstObject;`
34.  `//壓縮前原視頻寬高`
35.  `NSInteger videoWidth = videoTrack.naturalSize.width;`
36.  `NSInteger videoHeight = videoTrack.naturalSize.height;`
37.  `//壓縮前原視頻比特率`
38.  `NSInteger kbps = videoTrack.estimatedDataRate /  1024;`
39.  `//壓縮前原視頻幀率`
40.  `NSInteger frameRate =  [videoTrack nominalFrameRate];`
41.  `NSLog(@"\noriginalVideo\nfileSize = %.2f MB,\n videoWidth = %ld,\n videoHeight = %ld,\n video bitRate = %ld\n, video frameRate = %ld", fileSizeMB, videoWidth, videoHeight, kbps, frameRate);`
42.  `NSMutableDictionary  *dic =  [NSMutableDictionary dictionaryWithDictionary:@{@"urlStr"  : videoUrl.path}];`
43.  `//原視頻比特率小於指定比特率 不壓縮 返回原視頻`
44.  `if  (kbps <=  (compressBiteRate /  1024))  {`
45.  `compressComplete(dic);`
46.  `return;`
47.  `}`
48.  `//指定壓縮視頻沙盒根目錄`
49.  `NSString  *cachesDir =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask, YES) firstObject];`
50.  `//添加文件完整路徑`
51.  `NSString  *outputUrlStr =  [[cachesDir stringByAppendingPathComponent:@"videoTest"] stringByAppendingPathExtension:@"mp4"];`
52.  `NSLog(@"===壓縮視頻存放的指定路徑%@===", outputUrlStr);`
53.  `//如果指定路徑下已存在其他文件 先移除指定文件`
54.  `if  ([[NSFileManager defaultManager] fileExistsAtPath:outputUrlStr])  {`
55.  `BOOL removeSuccess =  [[NSFileManager defaultManager] removeItemAtPath:outputUrlStr error:nil];`
56.  `if  (!removeSuccess)  {`
57.  `[SVProgressHUD showErrorWithStatus:@"舊文件移除失敗"];`
58.  `return;`
59.  `}`
60.  `}`
61.  `//創建視頻文件讀取者`
62.  `AVAssetReader  *reader =  [AVAssetReader assetReaderWithAsset:asset error:nil];`
63.  `//從指定文件讀取視頻`
64.  `AVAssetReaderTrackOutput  *videoOutput =  [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:videoTrack outputSettings:[VideoCompress configVideoOutput]];`
65.  `//取出原視頻中音頻詳細資料`
66.  `AVAssetTrack  *audioTrack =  [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;`
67.  `//從音頻資料中讀取音頻`
68.  `AVAssetReaderTrackOutput  *audioOutput =  [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:[VideoCompress configAudioOutput]];`
69.  `//將讀取到的視頻信息添加到讀者隊列中`
70.  `if  ([reader canAddOutput:videoOutput])  {`
71.  `[reader addOutput:videoOutput];`
72.  `}`
73.  `//將讀取到的音頻信息添加到讀者隊列中`
74.  `if  ([reader canAddOutput:audioOutput])  {`
75.  `[reader addOutput:audioOutput];`
76.  `}`
77.  `//視頻文件寫入者`
78.  `AVAssetWriter  *writer =  [AVAssetWriter assetWriterWithURL:[NSURL fileURLWithPath:outputUrlStr] fileType:AVFileTypeMPEG4 error:nil];`
79.  `//根據指定配置創建寫入的視頻文件`
80.  `AVAssetWriterInput  *videoInput =  [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:[VideoCompress videoCompressSettingsWithBitRate:compressBiteRate withFrameRate:compressFrameRate withWidth:compressWidth WithHeight:compressHeight withOriginalWidth:videoWidth withOriginalHeight:videoHeight]];`
81.  `//根據指定配置創建寫入的音頻文件`
82.  `AVAssetWriterInput  *audioInput =  [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:[VideoCompress audioCompressSettings]];`
83.  `if  ([writer canAddInput:videoInput])  {`
84.  `[writer addInput:videoInput];`
85.  `NSLog(@"videoInput==========videoInput");`
86.  `}`
87.  `if  ([writer canAddInput:audioInput])  {`
88.  `[writer addInput:audioInput];`
89.  `NSLog(@"audioInput==========audioInput");`
90.  `}`
91.  `[SVProgressHUD showWithStatus:@"視頻壓縮中..."];`
92.  `[reader startReading];`
93.  `[writer startWriting];`
94.  `[writer startSessionAtSourceTime:kCMTimeZero];`
95.  `//創建視頻寫入隊列`
96.  `dispatch_queue_t videoQueue =  dispatch_queue_create("Video Queue", DISPATCH_QUEUE_SERIAL);`
97.  `//創建音頻寫入隊列`
98.  `dispatch_queue_t audioQueue =  dispatch_queue_create("Audio Queue", DISPATCH_QUEUE_SERIAL);`
99.  `//創建一個線程組`
100.  `dispatch_group_t  group  =  dispatch_group_create();`
101.  `//進入線程組`
102.  `dispatch_group_enter(group);`
103.  `//隊列準備好後 usingBlock`
104.  `[videoInput requestMediaDataWhenReadyOnQueue:videoQueue usingBlock:^{`
105.  `BOOL completedOrFailed = NO;`
106.  `while  ([videoInput isReadyForMoreMediaData]  &&  !completedOrFailed)  {`
107.  `CMSampleBufferRef sampleBuffer =  [videoOutput copyNextSampleBuffer];`
108.  `if  (sampleBuffer !=  NULL)  {`
109.  `[videoInput appendSampleBuffer:sampleBuffer];`
110.  `NSLog(@"===%@===", sampleBuffer);`
111.  `CFRelease(sampleBuffer);`
112.  `}  else  {`
113.  `completedOrFailed = YES;`
114.  `[videoInput markAsFinished];`
115.  `dispatch_group_leave(group);`
116.  `}`
117.  `}`
118.  `}];`
119.  `dispatch_group_enter(group);`
120.  `//隊列準備好後 usingBlock`
121.  `[audioInput requestMediaDataWhenReadyOnQueue:audioQueue usingBlock:^{`
122.  `BOOL completedOrFailed = NO;`
123.  `while  ([audioInput isReadyForMoreMediaData]  &&  !completedOrFailed)  {`
124.  `CMSampleBufferRef sampleBuffer =  [audioOutput copyNextSampleBuffer];`
125.  `if  (sampleBuffer !=  NULL)  {`
126.  `BOOL success =  [audioInput appendSampleBuffer:sampleBuffer];`
127.  `NSLog(@"===%@===", sampleBuffer);`
128.  `CFRelease(sampleBuffer);`
129.  `completedOrFailed =  !success;`
130.  `}  else  {`
131.  `completedOrFailed = YES;`
132.  `}`
133.  `}`
134.  `if  (completedOrFailed)  {`
135.  `[audioInput markAsFinished];`
136.  `dispatch_group_leave(group);`
137.  `}`
138.  `}];`
139.  `//完成壓縮`
140.  `dispatch_group_notify(group,  dispatch_get_main_queue(),  ^{`
141.  `if  ([reader status]  ==  AVAssetReaderStatusReading)  {`
142.  `[reader cancelReading];`
143.  `}`
144.  `switch  (writer.status)  {`
145.  `case  AVAssetWriterStatusWriting:`
146.  `{`
147.  `[SVProgressHUD showSuccessWithStatus:@"視頻壓縮完成"];`
148.  `[writer finishWritingWithCompletionHandler:^{`
149.  `[dic setObject:outputUrlStr forKey:@"urlStr"];`
150.  `compressComplete(dic);`
151.  `}];`
152.  `}`
153.  `break;`
154.  `case  AVAssetWriterStatusCancelled:`
155.  `[SVProgressHUD showInfoWithStatus:@"取消壓縮"];`
156.  `break;`
157.  `case  AVAssetWriterStatusFailed:`
158.  `NSLog(@"===error:%@===", writer.error);`
159.  `[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",writer.error]];`
160.  `break;`
161.  `case  AVAssetWriterStatusCompleted:`
162.  `{`
163.  `[SVProgressHUD showSuccessWithStatus:@"視頻壓縮完成"];`
164.  `[writer finishWritingWithCompletionHandler:^{`
165.  `[dic setObject:outputUrlStr forKey:@"urlStr"];`
166.  `compressComplete(dic);`
167.  `}];`
168.  `}`
169.  `break;`
170.  `default:`
171.  `break;`
172.  `}`
173.  `});`
174.  `}`

視頻壓縮的參數配置

1.  `+  (NSDictionary  *)videoCompressSettingsWithBitRate:(NSInteger)biteRate withFrameRate:(NSInteger)frameRate withWidth:(NSInteger)width WithHeight:(NSInteger)height withOriginalWidth:(NSInteger)originalWidth withOriginalHeight:(NSInteger)originalHeight{`
2.  `/*`
3.  `* AVVideoAverageBitRateKey: 比特率(碼率)每秒傳輸的文件大小 kbps`
4.  `* AVVideoExpectedSourceFrameRateKey:幀率 每秒播放的幀數`
5.  `* AVVideoProfileLevelKey:畫質水平`
6.  `BP-Baseline Profile:基本畫質。支持I/P 幀,只支持無交錯(Progressive)和CAVLC;`
7.  `EP-Extended profile:進階畫質。支持I/P/B/SP/SI 幀,只支持無交錯(Progressive)和CAVLC;`
8.  `MP-Main profile:主流畫質。提供I/P/B 幀,支持無交錯(Progressive)和交錯(Interlaced),也支持CAVLC 和CABAC 的支持;`
9.  `HP-High profile:高級畫質。在main Profile 的基礎上增加了8×8內部預測、自定義量化、 無損視頻編碼和更多的YUV 格式;`
10.  `**/`
11.  `NSInteger returnWidth = originalWidth > originalHeight ? width : height;`
12.  `NSInteger returnHeight = originalWidth > originalHeight ? height : width;`

14.  `NSDictionary  *compressProperties =  @{`
15.  `AVVideoAverageBitRateKey  :  @(biteRate),`
16.  `AVVideoExpectedSourceFrameRateKey  :  @(frameRate),`
17.  `AVVideoProfileLevelKey  :  AVVideoProfileLevelH264HighAutoLevel`
18.  `};`
19.  `if  (@available(iOS 11.0,  *))  {`
20.  `NSDictionary  *compressSetting =  @{`
21.  `AVVideoCodecKey  :  AVVideoCodecTypeH264,`
22.  `AVVideoWidthKey  :  @(returnWidth),`
23.  `AVVideoHeightKey  :  @(returnHeight),`
24.  `AVVideoCompressionPropertiesKey  : compressProperties,`
25.  `AVVideoScalingModeKey  :  AVVideoScalingModeResizeAspectFill`
26.  `};`
27.  `return compressSetting;`
28.  `}else  {`
29.  `NSDictionary  *compressSetting =  @{`
30.  `AVVideoCodecKey  :  AVVideoCodecTypeH264,`
31.  `AVVideoWidthKey  :  @(returnWidth),`
32.  `AVVideoHeightKey  :  @(returnHeight),`
33.  `AVVideoCompressionPropertiesKey  : compressProperties,`
34.  `AVVideoScalingModeKey  :  AVVideoScalingModeResizeAspectFill`
35.  `};`
36.  `return compressSetting;`
37.  `}`
38.  `}`

音頻壓縮的參數配置

1.  `//音頻設置`
2.  `+  (NSDictionary  *)audioCompressSettings{`
3.  `AudioChannelLayout stereoChannelLayout =  {`
4.  `.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo,`
5.  `.mChannelBitmap = kAudioChannelBit_Left,`
6.  `.mNumberChannelDescriptions =  0,`
7.  `};`
8.  `NSData  *channelLayoutAsData =  [NSData dataWithBytes:&stereoChannelLayout length:offsetof(AudioChannelLayout, mChannelDescriptions)];`
9.  `NSDictionary  *audioCompressSettings =  @{`
10.  `AVFormatIDKey  :  @(kAudioFormatMPEG4AAC),`
11.  `AVEncoderBitRateKey  :  @(128000),`
12.  `AVSampleRateKey  :  @(44100),`
13.  `AVNumberOfChannelsKey  :  @(2),`
14.  `AVChannelLayoutKey  : channelLayoutAsData`
15.  `};`
16.  `return audioCompressSettings;`
17.  `}`

讀取音頻參數配置

1.  `/** 音頻解碼 */`
2.  `+  (NSDictionary  *)configAudioOutput`
3.  `{`
4.  `NSDictionary  *audioOutputSetting =  @{`
5.  `AVFormatIDKey:  @(kAudioFormatLinearPCM)`
6.  `};`
7.  `return audioOutputSetting;`
8.  `}`

讀取視頻參數配置

1.  `/** 視頻解碼 */`
2.  `+  (NSDictionary  *)configVideoOutput`
3.  `{`
4.  `NSDictionary  *videoOutputSetting =  @{`
5.  `(__bridge NSString  *)kCVPixelBufferPixelFormatTypeKey:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_422YpCbCr8],`
6.  `(__bridge NSString  *)kCVPixelBufferIOSurfacePropertiesKey:[NSDictionary dictionary]`
7.  `};`

9.  `return videoOutputSetting;`
10.  `}`

githubDemo鏈接

如果你正在跳槽或者正準備跳槽不妨動動小手,添加一下咱們的交流羣1012951431來獲取一份詳細的大廠面試資料爲你的跳槽多添一份保障。

文末推薦:iOS熱門文集

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章