iOS視頻流采集概述(AVCaptureSession)

需求:需要采集到視頻幀數據從而可以進行一系列處理(如: 裁剪,旋轉,美顏,特效....). 所以,必須采集到視頻幀數據.


閱讀前提:

  • 使用AVFoundation框架
  • 采集音視頻幀數據

GitHub地址(附代碼) : iOS視頻流采集概述

簡書地址 : iOS視頻流采集概述

博客地址 : iOS視頻流采集概述

掘金地址 : iOS視頻流采集概述


注意:本文僅僅是原理性講解,而實際相機的設置也是比較復雜,具體相機參數的設置請參考另一篇 - iOS相機設置實戰


Overview

AVCaptureSession:使用相機或麥克風實時采集音視頻數據流.

  • AVCaptureSession : 管理輸入輸出音視頻流

  • AVCaptureDevice : 相機硬件的接口,用于控制硬件特性,諸如鏡頭的位置(前后攝像頭)、曝光、閃光燈等。

  • AVCaptureInput : 配置輸入設備,提供來自設備的數據

  • AVCaptureOutput : 管理輸出的結果(音視頻數據流)

  • AVCaptureConnection: 表示輸入與輸出的連接

  • AVCaptureVideoPreviewLayer: 顯示當前相機正在采集的狀況

一個session可以配置多個輸入輸出

1.AVCaptureSession

下圖展示了向session中添加輸入輸出后的連接情況

2.AVCaptureConnection

授權

首先需要在Info.plist文件中添加鍵Privacy - Camera Usage Description以請求相機權限.

注意: 如果不添加,程序crash,如果用戶不給權限,則會顯示全黑的相機畫面.

1. 使用Capture Session管理數據流

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幀...,原先setActiveVideoMinFrameDurationsetActiveVideoMaxFrameDuration是無法做到的,Apple規定我們需要使用新的方法設置幀率setActiveVideoMinFrameDurationsetActiveVideoMaxFrameDuration,并且該方法必須配合新的設置分辨率activeFormat的方法一起使用.

新的設置分辨率的方法activeFormatsessionPreset是互斥的,如果使用了一個, 另一個會失效,建議直接使用高幀率的設置方法,廢棄低幀率下設置方法,避免產生兼容問題。

Apple在更新方法后將原先分離的分辨率與幀率的設置方法合二為一,原先是單獨設置相機分辨率與幀率,而現在則需要一起設置,即每個分辨率有其對應支持的幀率范圍,每個幀率也有其支持的分辨率,需要我們遍歷來查詢,所以原先統一的單獨的設置分辨率與幀率的方法在高幀率模式下相當于棄用,可以根據項目需求選擇,如果確定項目不會支持高幀率(fps>30),可以使用以前的方法,簡單且有效.

注意: 使用activeFormat方法后,之前使用sessionPreset方法設置的分辨率將自動變為AVCaptureSessionPresetInputPriority,所以如果項目之前有用canSetSessionPreset比較的if語句也都將失效,建議如果項目必須支持高幀率則徹底啟用sessionPreset方法.

具體設置方法參考另一篇文章:iOS相機設置實戰

注意: 在將session配置為使用用于高分辨率靜態拍攝的活動格式并將以下一個或多個操作應用于AVCaptureVideoDataOutput時,系統可能無法滿足目標幀速率:縮放,方向更改,格式轉換。

1.2. 更改相機設置

如果你需要在開啟相機后進一步調節相機參數,在beginConfigurationcommitConfiguration中寫入更改的代碼.調用beginConfiguration后可以添加移除輸入輸出,更改分辨率,配置個別的輸入輸出屬性,直到調用commitConfiguration所有的更改才會生效.

[session beginConfiguration];
// Remove an existing capture device.
// Add a new capture device.
// Reset the preset.
[session commitConfiguration];



1.3. 監聽Session狀態

可以使用通知監聽相機當前狀態,如開始,停止,意外中斷等等...

  • 監聽掉幀
- (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的devicesdevicesWithMediaType:方法可以找到我們需要的設備, 可用設備列表可能會發生變化, 如它們被別的應用使用,或一個新的輸入設備接入(如耳機),通過注冊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: 自動調節曝光模式
    • 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: 自動開啟,根據光線判斷
hasFlash:是否有閃光燈
isFlashModeSupported:是否支持閃光燈模式
  • 手電筒模式-Torch Mode
    • AVCaptureTorchModeOff
    • AVCaptureTorchModeOn
    • AVCaptureTorchModeAuto
hasTorch: 是否有手電筒
isTorchModeSupported: 是否支持手電筒模式

手電筒只有在相機開啟時才能打開

  • 視頻穩定性-Video Stabilization
    • videoStabilizationEnabled
    • enablesVideoStabilizationWhenAvailable

該功能默認是關閉的,畫面穩定功能依賴于設備特定的硬件,并且不是所有格式的元數據與分辨率都支持此功能.

開啟該功能可能造成畫面延遲

  • 白平衡-White Balance
    • AVCaptureWhiteBalanceModeLocked
    • AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance
isWhiteBalanceModeSupported: 是否支持白平衡模式
adjustingWhiteBalance: 是否正在調整白平衡

相機為了適應不同類型的光照條件需要補償。這意味著在冷光線的條件下,傳感器應該增強紅色部分,而在暖光線下增強藍色部分。在 iPhone 相機中,設備會自動決定合適的補光,但有時也會被場景的顏色所混淆失效。幸運地是,iOS 8 可以里手動控制白平衡。

自動模式工作方式和對焦、曝光的方式一樣,但是沒有“感興趣的點”,整張圖像都會被納入考慮范圍。在手動模式,我們可以通過開爾文所表示的溫度來調節色溫和色彩。典型的色溫值在 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代表一種或多種媒體數據,比如,輸入設備可以同時提供視頻和音頻數據.每種媒體流代表一個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: 將數據寫入文件
  • AVCaptureVideoDataOutput: 將視頻數據以回調形式輸出視頻幀
  • AVCaptureAudioDataOutput: 將音頻數據以回調形式輸出音頻幀
  • AVCaptureStillImageOutput: 捕捉靜態圖片
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: 使用此類作為輸出.可以配置錄制最長時間,文件大小以及禁止在磁盤空間不足時繼續錄制等等.

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以及代理去監聽狀態,這個代理是AVCaptureFileOutputRecordingDelegate, 必須實現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. 獲取視頻幀數據

AVCaptureVideoDataOutput對象可以通過代理(setSampleBufferDelegate:queue:)獲取實時的視頻幀數據.同時需要指定一個接受視頻幀的串行隊列.

必須使用串行隊列,因為要保證視頻幀是按順序傳輸給代理方法

captureOutput:didOutputSampleBuffer:fromConnection:代理方法中接受視頻幀,每個視頻幀被存放在CMSampleBufferRef引用對象中, 默認這些buffers以相機最有效的格式發出,我們也可以通過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元數據的靜止圖像,需要使用AVCaptureStillImageOutput.

  • 像素與編碼格式

使用availableImageDataCVPixelFormatTypes, availableImageDataCodecTypes獲取當前支持的格式,以便于查詢是否支持你想要設置的格式.

AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = @{ AVVideoCodecKey : AVVideoCodecJPEG};
[stillImageOutput setOutputSettings:outputSettings];
  • 采集圖像

向output發送一條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已經開始工作,我們可以為用戶創建一個預覽圖展示當前相機采集的狀況(即就像系統相機拍攝視頻時的預覽界面)

5.1. Video Preview

  • AVCaptureVideoPreviewLayer: 展示相機預覽情況,CALayer的子類.
  • 使用AVCaptureVideoDataOutput可以將像素層呈現給用戶

a video preview layer保持對它關聯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的行為,你可以對這一圖層執行轉換,旋轉等操作.

5.1.1. 視頻重力感應模式
  • AVLayerVideoGravityResizeAspect: 保持分辨率的原始尺寸,即橫縱比,未填充的屏幕區域會有黑條
  • AVLayerVideoGravityResizeAspectFill: 保持橫縱比,鋪滿屏幕時可以犧牲部分像素
  • AVLayerVideoGravityResize: 拉伸視頻以充滿屏幕,圖像會失真
5.1.2. 點擊聚焦

實現帶有預覽層的對焦時,必須考慮預覽層的預覽方向和重力以及鏡像預覽的可能性.

5.2. 顯示Audio Levels

注意:一般采集音頻不使用AVCaptureSession, 而是用更底層的AudioQueue, AudioUnit, 如需幫助請參考另一篇文章: 音頻采集

使用AVCaptureAudioChannel對象監視捕獲連接中音頻通道的平均功率和峰值功率級別.音頻級不支持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. 流程

  • 創建AVCaptureSession對象管理輸入輸出流
  • 創建AVCaptureDevice對象管理當前硬件支持的所有設備,可以遍歷找到我們需要的設備
  • 創建AVCaptureDeviceInput對象表示具體的的輸入端的硬件設備
  • 創建AVCaptureVideoDataOutput對象管理輸出視頻幀
  • 實現AVCaptureVideoDataOutput代理方法以產生視頻幀
  • 將視頻幀從CMSampleBuffer格式轉為UIImage格式

下面是簡單流程實現

  • 創建并配置session對象
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;

  • 創建并配置設備的輸入端
AVCaptureDevice *device =
        [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 
NSError *error = nil;
AVCaptureDeviceInput *input =
        [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
}
[session addInput:input];

  • 創建并配置輸出端

通過配置AVCaptureVideoDataOutput對象(如視頻幀的格式, 幀率),以產生未壓縮的原始數據.

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);

  • 實現代理方法
- (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是一個同步的方法,它可能會花一些時間,因此可能阻塞線程(可以在同步隊列中執行避免主線程阻塞).

7. 補充

iOS7.0 介紹了高幀率視頻采集,我們需要使用AVCaptureDeviceFormat類,該類具有返回支持的圖像類型,幀率,縮放比例,是否支持穩定性等等.

  • 支持720p, 60幀,同時保證視頻穩定性
  • 兼容音頻的倍速播放
  • 編輯支持可變組合中的縮放編輯 (Editing has full support for scaled edits in mutable compositions.)
  • 導出可以支持可變幀率的60fps或者將其轉為較低幀率如30fps

7.1. 播放

AVPlayer的一個實例通過設置setRate:方法值自動管理大部分播放速度。該值用作播放速度的乘數。值為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;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容