需求:需要采集到視頻幀數(shù)據(jù)從而可以進行一系列處理(如: 裁剪手负,旋轉拴魄,美顏汛骂,特效....). 所以,必須采集到視頻幀數(shù)據(jù).
閱讀前提:
- 使用AVFoundation框架
- 采集音視頻幀數(shù)據(jù)
GitHub地址(附代碼) : iOS視頻流采集概述
簡書地址 : iOS視頻流采集概述
博客地址 : iOS視頻流采集概述
掘金地址 : iOS視頻流采集概述
注意:本文僅僅是原理性講解,而實際相機的設置也是比較復雜溯街,具體相機參數(shù)的設置請參考另一篇 - iOS相機設置實戰(zhàn)
Overview
AVCaptureSession:使用相機或麥克風實時采集音視頻數(shù)據(jù)流.
AVCaptureSession : 管理輸入輸出音視頻流
AVCaptureDevice : 相機硬件的接口,用于控制硬件特性诱桂,諸如鏡頭的位置(前后攝像頭)、曝光呈昔、閃光燈等挥等。
AVCaptureInput : 配置輸入設備,提供來自設備的數(shù)據(jù)
AVCaptureOutput : 管理輸出的結果(音視頻數(shù)據(jù)流)
AVCaptureConnection: 表示輸入與輸出的連接
AVCaptureVideoPreviewLayer: 顯示當前相機正在采集的狀況
一個session可以配置多個輸入輸出
下圖展示了向session中添加輸入輸出后的連接情況
授權
首先需要在Info.plist文件中添加鍵Privacy - Camera Usage Description
以請求相機權限.
注意: 如果不添加,程序crash,如果用戶不給權限,則會顯示全黑的相機畫面.
1. 使用Capture Session管理數(shù)據(jù)流
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Add inputs and outputs.
[session startRunning];
1.1. 使用preset配置分辨率,幀率
- canSetSessionPreset:檢查是否支持指定分辨率
- setActiveVideoMinFrameDuration: 設置幀率最小值
- setActiveVideoMaxFrameDuration: 設置幀率最大值
CMTimeMake: 分子為1,即每秒鐘來多少幀.
- 在低幀率下(幀率<=30)可以用如下方式設置
- (void)setCameraResolutionByPresetWithHeight:(int)height session:(AVCaptureSession *)session {
[session beginConfiguration];
session.sessionPreset = preset;
[session commitConfiguration];
}
- (void)setCameraForLFRWithFrameRate:(int)frameRate {
// Only for frame rate <= 30
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[captureDevice lockForConfiguration:NULL];
[captureDevice setActiveVideoMinFrameDuration:CMTimeMake(1, frameRate)];
[captureDevice setActiveVideoMaxFrameDuration:CMTimeMake(1, frameRate)];
[captureDevice unlockForConfiguration];
}
- 高幀率下設置分辨率(幀率>30)
如果需要對某一分辨率支持高幀率的設置,如50幀,60幀,120幀...,原先setActiveVideoMinFrameDuration
與setActiveVideoMaxFrameDuration
是無法做到的,Apple規(guī)定我們需要使用新的方法設置幀率setActiveVideoMinFrameDuration
與setActiveVideoMaxFrameDuration
,并且該方法必須配合新的設置分辨率activeFormat
的方法一起使用.
新的設置分辨率的方法activeFormat
與sessionPreset
是互斥的,如果使用了一個, 另一個會失效,建議直接使用高幀率的設置方法堤尾,廢棄低幀率下設置方法肝劲,避免產生兼容問題。
Apple在更新方法后將原先分離的分辨率與幀率的設置方法合二為一,原先是單獨設置相機分辨率與幀率,而現(xiàn)在則需要一起設置,即每個分辨率有其對應支持的幀率范圍,每個幀率也有其支持的分辨率,需要我們遍歷來查詢,所以原先統(tǒng)一的單獨的設置分辨率與幀率的方法在高幀率模式下相當于棄用,可以根據(jù)項目需求選擇,如果確定項目不會支持高幀率(fps>30),可以使用以前的方法,簡單且有效.
注意: 使用
activeFormat
方法后,之前使用sessionPreset
方法設置的分辨率將自動變?yōu)?code>AVCaptureSessionPresetInputPriority,所以如果項目之前有用canSetSessionPreset
比較的if語句也都將失效,建議如果項目必須支持高幀率則徹底啟用sessionPreset
方法.
具體設置方法參考另一篇文章:iOS相機設置實戰(zhàn)
注意: 在將session配置為使用用于高分辨率靜態(tài)拍攝的活動格式并將以下一個或多個操作應用于AVCaptureVideoDataOutput時郭宝,系統(tǒng)可能無法滿足目標幀速率:縮放辞槐,方向更改,格式轉換粘室。
1.2. 更改相機設置
如果你需要在開啟相機后進一步調節(jié)相機參數(shù),在beginConfiguration
和commitConfiguration
中寫入更改的代碼.調用beginConfiguration
后可以添加移除輸入輸出,更改分辨率,配置個別的輸入輸出屬性,直到調用commitConfiguration
所有的更改才會生效.
[session beginConfiguration];
// Remove an existing capture device.
// Add a new capture device.
// Reset the preset.
[session commitConfiguration];
1.3. 監(jiān)聽Session狀態(tài)
可以使用通知監(jiān)聽相機當前狀態(tài),如開始,停止,意外中斷等等...
- 監(jiān)聽掉幀
- (void)captureOutput:(AVCaptureOutput *)output didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
- 處理相機運行中突然出錯
[kTVUNotification addObserver:self selector:@selector(handleCameraRuntimeError)
name:AVCaptureSessionRuntimeErrorNotification
object:nil];
[kTVUNotification addObserver:self selector:@selector(handleCameraInterruptionEndedError)
name:AVCaptureSessionInterruptionEndedNotification
object:nil];
[kTVUNotification addObserver:self selector:@selector(handleCameraWasInterruptedError)
name:AVCaptureSessionWasInterruptedNotification
object:nil];
2. AVCaptureDevice表示輸入設備
2.1. 定義
AVCaptureDevice對象是關于相機硬件的接口,用于控制硬件特性榄檬,諸如鏡頭的位置、曝光衔统、閃光燈等鹿榜。
2.2. 獲取設備
使用AVCaptureDevice的devices
和 devicesWithMediaType:
方法可以找到我們需要的設備, 可用設備列表可能會發(fā)生變化, 如它們被別的應用使用,或一個新的輸入設備接入(如耳機),通過注冊AVCaptureDeviceWasConnectedNotification,AVCaptureDeviceWasDisconnectedNotification可以在設備變化時得到通知.
2.3. 設備特性
可以通過代碼獲取當前輸入設備的位置(前后置攝像頭)以及其他硬件相關信息.
NSArray *devices = [AVCaptureDevice devices];
for (AVCaptureDevice *device in devices) {
NSLog(@"Device name: %@", [device localizedName]);
if ([device hasMediaType:AVMediaTypeVideo]) {
if ([device position] == AVCaptureDevicePositionBack) {
NSLog(@"Device position : back");
}
else {
NSLog(@"Device position : front");
}
}
}
2.4. 相機功能設置
不同設備具有不同的功能,如果需要可以開啟對應的功能
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
NSMutableArray *torchDevices = [[NSMutableArray alloc] init];
for (AVCaptureDevice *device in devices) {
[if ([device hasTorch] &&
[device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]) {
[torchDevices addObject:device];
}
}
注意:在設置相機屬性前,總是先通過API查詢當前設備是否支持該功能,再進行相應處理
- 聚焦模式-Focus Modes
- AVCaptureFocusModeLocked: 設置一個固定的聚焦點
- AVCaptureFocusModeAutoFocus: 首次自動對焦然后鎖定一個聚焦點
- AVCaptureFocusModeContinuousAutoFocus: 指當場景改變,相機會自動重新對焦到畫面的中心點
isFocusModeSupported: 查詢設備是否支持.
adjustingFocus: 判斷一個設備是否正在改變對焦點
使用focusPointOfInterestSupported
測試設備是否支持設置對焦點,如果支持,使用focusPointOfInterest
設置聚焦點,{0,0}代表畫面左上角坐標,{1,1}代表右下角坐標.
if ([currentDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
CGPoint autofocusPoint = CGPointMake(0.5f, 0.5f);
[currentDevice setFocusPointOfInterest:autofocusPoint];
[currentDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
}
- 曝光模式-Exposure Modes
- AVCaptureExposureModeContinuousAutoExposure: 自動調節(jié)曝光模式
- AVCaptureExposureModeLocked: 固定的曝光模式
isExposureModeSupported:是否支持某個曝光模式
adjustingExposure:判斷一個設備是否正在改變曝光值
if ([currentDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
CGPoint exposurePoint = CGPointMake(0.5f, 0.5f);
[currentDevice setExposurePointOfInterest:exposurePoint];
[currentDevice setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}
- 閃光燈模式-Flash Modes
- AVCaptureFlashModeOff: 永不開啟
- AVCaptureFlashModeOn: 總是開啟
- AVCaptureFlashModeAuto: 自動開啟,根據(jù)光線判斷
hasFlash:是否有閃光燈
isFlashModeSupported:是否支持閃光燈模式
- 手電筒模式-Torch Mode
- AVCaptureTorchModeOff
- AVCaptureTorchModeOn
- AVCaptureTorchModeAuto
hasTorch: 是否有手電筒
isTorchModeSupported: 是否支持手電筒模式
手電筒只有在相機開啟時才能打開
- 視頻穩(wěn)定性-Video Stabilization
- videoStabilizationEnabled
- enablesVideoStabilizationWhenAvailable
該功能默認是關閉的,畫面穩(wěn)定功能依賴于設備特定的硬件,并且不是所有格式的元數(shù)據(jù)與分辨率都支持此功能.
開啟該功能可能造成畫面延遲
- 白平衡-White Balance
- AVCaptureWhiteBalanceModeLocked
- AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance
isWhiteBalanceModeSupported: 是否支持白平衡模式
adjustingWhiteBalance: 是否正在調整白平衡
相機為了適應不同類型的光照條件需要補償锦爵。這意味著在冷光線的條件下舱殿,傳感器應該增強紅色部分,而在暖光線下增強藍色部分棉浸。在 iPhone 相機中怀薛,設備會自動決定合適的補光刺彩,但有時也會被場景的顏色所混淆失效迷郑。幸運地是枝恋,iOS 8 可以里手動控制白平衡。
自動模式工作方式和對焦嗡害、曝光的方式一樣焚碌,但是沒有“感興趣的點”,整張圖像都會被納入考慮范圍霸妹。在手動模式十电,我們可以通過開爾文所表示的溫度來調節(jié)色溫和色彩。典型的色溫值在 2000-3000K (類似蠟燭或燈泡的暖光源) 到 8000K (純凈的藍色天空) 之間叹螟。色彩范圍從最小的 -150 (偏綠) 到 150 (偏品紅)鹃骂。
- 設置設備方向
- AVCaptureConnectionsupportsVideoOrientation:
AVCaptureConnection *captureConnection = <#A capture connection#>;
if ([captureConnection isVideoOrientationSupported])
{
AVCaptureVideoOrientation orientation = AVCaptureVideoOrientationLandscapeLeft;
[captureConnection setVideoOrientation:orientation];
}
- 配置設備
使用鎖配置相機屬性,lockForConfiguration:
,為了避免在你修改它時其他應用程序可能對它做更改.
if ([device isFocusModeSupported:AVCaptureFocusModeLocked]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.focusMode = AVCaptureFocusModeLocked;
[device unlockForConfiguration];
}
else {
// Respond to the failure as appropriate.
- 切換設備
AVCaptureSession *session = <#A capture session#>;
[session beginConfiguration];
[session removeInput:frontFacingCameraDeviceInput];
[session addInput:backFacingCameraDeviceInput];
[session commitConfiguration];
3. 配置Capture Inputs添加到Session中
一個AVCaptureInput代表一種或多種媒體數(shù)據(jù),比如,輸入設備可以同時提供視頻和音頻數(shù)據(jù).每種媒體流代表一個AVCaptureInputPort對象.使用AVCaptureConnection可以將AVCaptureInputPort與AVCaptureOutput連接起來.
NSError *error;
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
}
AVCaptureSession *captureSession = <#Get a capture session#>;
AVCaptureDeviceInput *captureDeviceInput = <#Get a capture device input#>;
if ([captureSession canAddInput:captureDeviceInput]) {
[captureSession addInput:captureDeviceInput];
}
else {
// Handle the failure.
}
4. 使用Capture Outputs從Session中獲取輸出流
AVCaptureOutput: 從session中獲取輸出流.
- AVCaptureMovieFileOutput: 將數(shù)據(jù)寫入文件
- AVCaptureVideoDataOutput: 將視頻數(shù)據(jù)以回調形式輸出視頻幀
- AVCaptureAudioDataOutput: 將音頻數(shù)據(jù)以回調形式輸出音頻幀
- AVCaptureStillImageOutput: 捕捉靜態(tài)圖片
addOutput: 添加輸出
canAddOutput: 是否能添加
AVCaptureSession *captureSession = <#Get a capture session#>;
AVCaptureMovieFileOutput *movieOutput = <#Create and configure a movie output#>;
if ([captureSession canAddOutput:movieOutput]) {
[captureSession addOutput:movieOutput];
}
else {
// Handle the failure.
}
4.1. AVCaptureMovieFileOutput
4.1.1. 寫入文件
AVCaptureMovieFileOutput: 使用此類作為輸出.可以配置錄制最長時間,文件大小以及禁止在磁盤空間不足時繼續(xù)錄制等等.
AVCaptureMovieFileOutput *aMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
CMTime maxDuration = <#Create a CMTime to represent the maximum duration#>;
aMovieFileOutput.maxRecordedDuration = maxDuration;
aMovieFileOutput.minFreeDiskSpaceLimit = <#An appropriate minimum given the quality of the movie format and the duration#>;
4.1.2. 開始錄制
你需要提供一個文件保存地址的URL以及代理去監(jiān)聽狀態(tài),這個代理是AVCaptureFileOutputRecordingDelegate, 必須實現(xiàn)captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:
代理方法
URL不能是已經存在的文件,因為無法重寫.
AVCaptureMovieFileOutput *aMovieFileOutput = <#Get a movie file output#>;
NSURL *fileURL = <#A file URL that identifies the output location#>;
[aMovieFileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:<#The delegate#>];
4.1.3. 確保文件寫入成功
通過代理方法可以檢查是否寫入成功
需要檢查
AVErrorRecordingSuccessfullyFinishedKey
的值,因為可能寫入沒有錯誤,但由于磁盤內存不足導致最終寫入失敗.
寫入失敗的原因
- 磁盤內存不足(AVErrorDiskFull)
- 錄制設備失去連接(AVErrorDeviceWasDisconnected)
- session意外中斷(AVErrorSessionWasInterrupted)
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {
BOOL recordedSuccessfully = YES;
if ([error code] != noErr) {
// A problem occurred: Find out if the recording was successful.
id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
if (value) {
recordedSuccessfully = [value boolValue];
}
}
// Continue as appropriate...
4.1.4. 添加Metadata到文件
可以在任意時間設置輸出文件的metadata信息,即使正在錄制.
AVCaptureMovieFileOutput *aMovieFileOutput = <#Get a movie file output#>;
NSArray *existingMetadataArray = aMovieFileOutput.metadata;
NSMutableArray *newMetadataArray = nil;
if (existingMetadataArray) {
newMetadataArray = [existingMetadataArray mutableCopy];
}
else {
newMetadataArray = [[NSMutableArray alloc] init];
}
AVMutableMetadataItem *item = [[AVMutableMetadataItem alloc] init];
item.keySpace = AVMetadataKeySpaceCommon;
item.key = AVMetadataCommonKeyLocation;
CLLocation *location - <#The location to set#>;
item.value = [NSString stringWithFormat:@"%+08.4lf%+09.4lf/"
location.coordinate.latitude, location.coordinate.longitude];
[newMetadataArray addObject:item];
aMovieFileOutput.metadata = newMetadataArray;
4.2 AVCaptureVideoDataOutput
4.2.1. 獲取視頻幀數(shù)據(jù)
AVCaptureVideoDataOutput對象可以通過代理(setSampleBufferDelegate:queue:
)獲取實時的視頻幀數(shù)據(jù).同時需要指定一個接受視頻幀的串行隊列.
必須使用串行隊列,因為要保證視頻幀是按順序傳輸給代理方法
在captureOutput:didOutputSampleBuffer:fromConnection:
代理方法中接受視頻幀,每個視頻幀被存放在CMSampleBufferRef引用對象中, 默認這些buffers以相機最有效的格式發(fā)出,我們也可以通過videoSettings
指定輸出相機的格式.需要將要指定的格式設置為kCVPixelBufferPixelFormatTypeKey
的value,使用availableVideoCodecTypes
可以查詢當前支持的相機格式.
AVCaptureVideoDataOutput *videoDataOutput = [AVCaptureVideoDataOutput new];
NSDictionary *newSettings =
@{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };
videoDataOutput.videoSettings = newSettings;
// discard if the data output queue is blocked (as we process the still image
[videoDataOutput setAlwaysDiscardsLateVideoFrames:YES];)
// create a serial dispatch queue used for the sample buffer delegate as well as when a still image is captured
// a serial dispatch queue must be used to guarantee that video frames will be delivered in order
// see the header doc for setSampleBufferDelegate:queue: for more information
videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL);
[videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];
AVCaptureSession *captureSession = <#The Capture Session#>;
if ( [captureSession canAddOutput:videoDataOutput] )
[captureSession addOutput:videoDataOutput];
4.3. AVCaptureStillImageOutput
如果要使用附帶metadata元數(shù)據(jù)的靜止圖像,需要使用AVCaptureStillImageOutput
.
- 像素與編碼格式
使用availableImageDataCVPixelFormatTypes, availableImageDataCodecTypes
獲取當前支持的格式,以便于查詢是否支持你想要設置的格式.
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = @{ AVVideoCodecKey : AVVideoCodecJPEG};
[stillImageOutput setOutputSettings:outputSettings];
- 采集圖像
向output發(fā)送一條captureStillImageAsynchronouslyFromConnection:completionHandler:
消息以采集一張圖像.
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in stillImageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:
^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
CFDictionaryRef exifAttachments =
CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
if (exifAttachments) {
// Do something with the attachments.
}
// Continue as appropriate.
}];
5. 展示預覽圖
如果相機的session已經開始工作,我們可以為用戶創(chuàng)建一個預覽圖展示當前相機采集的狀況(即就像系統(tǒng)相機拍攝視頻時的預覽界面)
5.1. Video Preview
- AVCaptureVideoPreviewLayer: 展示相機預覽情況,CALayer的子類.
- 使用
AVCaptureVideoDataOutput
可以將像素層呈現(xiàn)給用戶
a video preview layer保持對它關聯(lián)session的強引用,為了確保在圖層嘗試顯示視頻時不會被釋放
AVCaptureSession *captureSession = <#Get a capture session#>;
CALayer *viewLayer = <#Get a layer from the view in which you want to present the preview#>;
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession];
[viewLayer addSublayer:captureVideoPreviewLayer];
preview layer是CALayer的子類,因此它具有CALayer的行為,你可以對這一圖層執(zhí)行轉換,旋轉等操作.
5.1.1. 視頻重力感應模式
- AVLayerVideoGravityResizeAspect: 保持分辨率的原始尺寸,即橫縱比,未填充的屏幕區(qū)域會有黑條
- AVLayerVideoGravityResizeAspectFill: 保持橫縱比,鋪滿屏幕時可以犧牲部分像素
- AVLayerVideoGravityResize: 拉伸視頻以充滿屏幕,圖像會失真
5.1.2. 點擊聚焦
實現(xiàn)帶有預覽層的對焦時,必須考慮預覽層的預覽方向和重力以及鏡像預覽的可能性.
5.2. 顯示Audio Levels
注意:一般采集音頻不使用AVCaptureSession, 而是用更底層的AudioQueue, AudioUnit, 如需幫助請參考另一篇文章: 音頻采集
使用AVCaptureAudioChannel對象監(jiān)視捕獲連接中音頻通道的平均功率和峰值功率級別.音頻級不支持KVO,因此必須經常輪詢更新級別罢绽,以便更新用戶界面(例如畏线,每秒10次)。
AVCaptureAudioDataOutput *audioDataOutput = <#Get the audio data output#>;
NSArray *connections = audioDataOutput.connections;
if ([connections count] > 0) {
// There should be only one connection to an AVCaptureAudioDataOutput.
AVCaptureConnection *connection = [connections objectAtIndex:0];
NSArray *audioChannels = connection.audioChannels;
for (AVCaptureAudioChannel *channel in audioChannels) {
float avg = channel.averagePowerLevel;
float peak = channel.peakHoldLevel;
// Update the level meter user interface.
}
}
6. 總結
下面將介紹如何采集視頻幀并將其轉換為UIImage對象.
6.1. 流程
- 創(chuàng)建AVCaptureSession對象管理輸入輸出流
- 創(chuàng)建AVCaptureDevice對象管理當前硬件支持的所有設備良价,可以遍歷找到我們需要的設備
- 創(chuàng)建AVCaptureDeviceInput對象表示具體的的輸入端的硬件設備
- 創(chuàng)建AVCaptureVideoDataOutput對象管理輸出視頻幀
- 實現(xiàn)AVCaptureVideoDataOutput代理方法以產生視頻幀
- 將視頻幀從CMSampleBuffer格式轉為UIImage格式
下面是簡單流程實現(xiàn)
- 創(chuàng)建并配置session對象
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
- 創(chuàng)建并配置設備的輸入端
AVCaptureDevice *device =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
}
[session addInput:input];
- 創(chuàng)建并配置輸出端
通過配置AVCaptureVideoDataOutput對象(如視頻幀的格式, 幀率),以產生未壓縮的原始數(shù)據(jù).
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
output.videoSettings =
@{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };
output.minFrameDuration = CMTimeMake(1, 15);
dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[output setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);
- 實現(xiàn)代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection {
UIImage *image = imageFromSampleBuffer(sampleBuffer);
// Add your code here that uses the image.
}
- 開始/停止錄制
配置完capture session之后,確保應用程序擁有權限.
NSString *mediaType = AVMediaTypeVideo;
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
if (granted)
{
//Granted access to mediaType
[self setDeviceAuthorized:YES];
}
else
{
//Not granted access to mediaType
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:@"AVCam!"
message:@"AVCam doesn't have permission to use Camera, please change privacy settings"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
[self setDeviceAuthorized:NO];
});
}
}];
[session startRunning];
[session stopRunning];
注意: startRunning是一個同步的方法,它可能會花一些時間,因此可能阻塞線程(可以在同步隊列中執(zhí)行避免主線程阻塞).
7. 補充
iOS7.0 介紹了高幀率視頻采集,我們需要使用AVCaptureDeviceFormat類,該類具有返回支持的圖像類型,幀率,縮放比例,是否支持穩(wěn)定性等等.
- 支持720p, 60幀,同時保證視頻穩(wěn)定性
- 兼容音頻的倍速播放
- 編輯支持可變組合中的縮放編輯 (Editing has full support for scaled edits in mutable compositions.)
- 導出可以支持可變幀率的60fps或者將其轉為較低幀率如30fps
7.1. 播放
AVPlayer的一個實例通過設置setRate:方法值自動管理大部分播放速度寝殴。該值用作播放速度的乘數(shù)。值為1.0會導致正常播放明垢,0.5以半速播放蚣常,5.0播放比正常播放快5倍,依此類推痊银。
AVPlayerItem對象支持audioTimePitchAlgorithm屬性抵蚊。此屬性允許您指定在使用“時間間距算法設置”常量以各種幀速率播放影片時播放音頻的方式。
7.2. 編輯
使用AVMutableComposition對象完成編輯操作
7.3. 導出
使用AVAssetExportSession
導出60fps的視頻文件
- AVAssetExportPresetPassthrough: 避免重新編碼視頻溯革。它將媒體的部分標記為部分60 fps泌射,部分減速或部分加速.
- frameDuration: 使用恒定幀速率導出以獲得最大的播放兼容性,可以使用audioTimePitchAlgorithm指定時間.
7.4. 錄制
使用AVCaptureMovieFileOutput自動支持高幀率的錄制,它將自動選擇正確的H264的音高與比特率.如果需要對錄制做一些額外操作,需要用到AVAssetWriter.
assetWriterInput.expectsMediaDataInRealTime=YES;