問:你有做過音視頻嗎?答:做過但是我們是用第三方的。對具體實現(xiàn)不是很清楚。
如果面試的時候你這么回答那大概率是沒有戲的,最近很多公司都有對音視頻類的需求,奈何大多數(shù)開發(fā)者沒有具體去研究過。這里我大概整理下iOS 如果自己實現(xiàn)一套視頻拍攝工具。
1.常用的類
- AVCaptureSession 捕捉繪畫
- 相當于插板的功能承接輸入和輸出
- AVCaptureDevice 捕捉設備
- AVMediaTypeVideo/AVMediaTypeAudio 不能直接給AVCaptureSession 使用 需要借助AVCaptureDeviceInput
- AVCaptureDeviceInput 源輸入
- AVCaptureVideoPreviewLayer 捕獲預覽
AVCaptureOutput 子類
- AVCaptureAudioDataOutput :一種捕獲輸出,用于記錄音頻,并在錄制音頻時提供對音頻樣本緩沖區(qū)的訪問。
- AVCaptureAudioPreviewOutput :一種捕獲輸出,與一個核心音頻輸出設備相關(guān)聯(lián)、可用于播放由捕獲會話捕獲的音頻。
- AVCaptureDepthDataOutput :在兼容的攝像機設備上記錄場景深度信息的捕獲輸出。
- AVCaptureMetadataOutput :用于處理捕獲會話AVCaptureSession產(chǎn)生的定時元數(shù)據(jù)的捕獲輸出。
- AVCaptureStillImageOutput :在macOS中捕捉靜止照片的捕獲輸出。該類在iOS 10.0中被棄用,并且不支持新的相機捕獲功能,例如原始圖像輸出和實時照片。在iOS 10.0或更高版本中,使用AVCapturePhotoOutput類代替。
- AVCapturePhotoOutput :靜態(tài)照片、動態(tài)照片和其他攝影工作流的捕獲輸出。
- AVCaptureVideoDataOutput :記錄視頻并提供對視頻幀進行處理的捕獲輸出。
- AVCaptureFileOutput :用于捕獲輸出的抽象超類,可將捕獲數(shù)據(jù)記錄到文件中。
- AVCaptureMovieFileOutput :繼承自AVCaptureFileOutput,將視頻和音頻記錄到QuickTime電影文件的捕獲輸出。
- AVCaptureAudioFileOutput :繼承自AVCaptureFileOutput,記錄音頻并將錄制的音頻保存到文件的捕獲輸出。
大概畫了下設置過程他們之前的設置關(guān)系如圖:

2.常用的設置方法
設置AVCaptureSession 設置輸入輸出源
//創(chuàng)建捕捉會話。AVCaptureSession 是捕捉場景的中心樞紐
self.captureSession = [[AVCaptureSession alloc]init];
// AVCaptureSessionPresetHigh
//AVCaptureSessionPresetMedium
//AVCaptureSessionPresetLow
// AVCaptureSessionPreset640x480
//AVCaptureSessionPreset1280x720
// AVCaptureSessionPresetPhoto
//設置圖像的分辨率
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
//拿到默認視頻捕捉設備 iOS系統(tǒng)返回后置攝像頭
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//將捕捉設備封裝成AVCaptureDeviceInput
//注意:為會話添加捕捉設備,必須將設備封裝成AVCaptureDeviceInput對象
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
//判斷videoInput是否有效
if (videoInput)
{
//canAddInput:測試是否能被添加到會話中
if ([self.captureSession canAddInput:videoInput])
{
//將videoInput 添加到 captureSession中
[self.captureSession addInput:videoInput];
self.activeVideoInput = videoInput;
}
}else
{
//創(chuàng)建失敗
}
//選擇默認音頻捕捉設備 即返回一個內(nèi)置麥克風
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
//為這個設備創(chuàng)建一個捕捉設備輸入
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
//判斷audioInput是否有效
if (audioInput) {
//canAddInput:測試是否能被添加到會話中
if ([self.captureSession canAddInput:audioInput])
{
//將audioInput 添加到 captureSession中
[self.captureSession addInput:audioInput];
}
}else
{
//創(chuàng)建失敗
}
//AVCaptureStillImageOutput 實例 從攝像頭捕捉靜態(tài)圖片
self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
//配置字典:希望捕捉到JPEG格式的圖片
self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
//輸出連接 判斷是否可用,可用則添加到輸出連接中去
if ([self.captureSession canAddOutput:self.imageOutput])
{
[self.captureSession addOutput:self.imageOutput];
}
//創(chuàng)建一個AVCaptureMovieFileOutput 實例,用于將Quick Time 電影錄制到文件系統(tǒng)
self.movieOutput = [[AVCaptureMovieFileOutput alloc]init];
//輸出連接 判斷是否可用,可用則添加到輸出連接中去
if ([self.captureSession canAddOutput:self.movieOutput])
{
[self.captureSession addOutput:self.movieOutput];
}
self.videoQueue = dispatch_queue_create("yc.VideoQueue", NULL);
//創(chuàng)建成功
}
開啟session
創(chuàng)建一個線程出去捕捉事件,當然一般來說錄制過程是要可見的,所以需要設置session的AVCaptureVideoPreviewLayer,然后將layer貼到你想顯示的view上用于捕捉預覽
{
//使用同步調(diào)用會損耗一定的時間,則用異步的方式處理
dispatch_async(self.videoQueue, ^{
[self.captureSession startRunning];
});
}
一切準備就緒就可以開始錄制了
//獲取當前視頻捕捉連接信息,用于捕捉視頻數(shù)據(jù)配置一些核心屬性
AVCaptureConnection * videoConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
//判斷是否支持設置videoOrientation 屬性。
if([videoConnection isVideoOrientationSupported])
{
//支持則修改當前視頻的方向
videoConnection.videoOrientation = [self currentVideoOrientation];
}
//判斷是否支持視頻穩(wěn)定 可以顯著提高視頻的質(zhì)量。只會在錄制視頻文件涉及
if([videoConnection isVideoStabilizationSupported])
{
videoConnection.enablesVideoStabilizationWhenAvailable = YES;
}
AVCaptureDevice *device = [self activeCamera];
//攝像頭可以進行平滑對焦模式操作。即減慢攝像頭鏡頭對焦速度。當用戶移動拍攝時攝像頭會嘗試快速自動對焦。
if (device.isSmoothAutoFocusEnabled) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.smoothAutoFocusEnabled = YES;
[device unlockForConfiguration];
}else
{
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
}
}
//查找寫入捕捉視頻的唯一文件系統(tǒng)URL.
self.outputURL = [self uniqueURL];
if (self.outputURL) {
//在捕捉輸出上調(diào)用方法 參數(shù)1:錄制保存路徑 參數(shù)2:代理
[self.movieOutput startRecordingToOutputFileURL:self.outputURL recordingDelegate:self];
}else{
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:[NSError errorWithDomain:@"fail" code:-10001 userInfo:@{@"msg":@"地址失敗"}]];
}
}
}
如果沒有報錯的話,視頻就會開始采集并寫入到你設置的到對應的沙盒地址中去
停止錄制
[self.movieOutput stopRecording];
停止錄制之后 可以在AVCaptureFileOutputRecordingDelegate回調(diào)方法中做對應的處理,比如視頻轉(zhuǎn)碼,存入相冊 等等。
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
當然拍攝過程中還會涉及到 切換攝像頭,自動曝光,自動對焦等等,下面大概列舉一下常用的方法
切換攝像頭
session beginConfiguration 做對應攝像頭輸入然后在commitConfiguration 提交配置
//判斷是否有多個攝像頭
if (![self canSwitchCameras])
{
return NO;
}
//獲取當前設備的反向設備
NSError *error;
AVCaptureDevice *videoDevice = [self inactiveCamera];
//將輸入設備封裝成AVCaptureDeviceInput
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
//判斷videoInput 是否為nil
if (videoInput)
{
//標注原配置變化開始
[self.captureSession beginConfiguration];
//將捕捉會話中,原本的捕捉輸入設備移除
[self.captureSession removeInput:self.activeVideoInput];
//判斷新的設備是否能加入
if ([self.captureSession canAddInput:videoInput])
{
//能加入成功,則將videoInput 作為新的視頻捕捉設備
[self.captureSession addInput:videoInput];
//將獲得設備 改為 videoInput
self.activeVideoInput = videoInput;
}else
{
//如果新設備,無法加入。則將原本的視頻捕捉設備重新加入到捕捉會話中
[self.captureSession addInput:self.activeVideoInput];
}
//配置完成后, AVCaptureSession commitConfiguration 會分批的將所有變更整合在一起。
[self.captureSession commitConfiguration];
}else
{
//創(chuàng)建AVCaptureDeviceInput 出現(xiàn)錯誤,則通知委托來處理該錯誤
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
return NO;
}
return YES;
}
閃光燈
因為攝像頭是功能的,所以打開攝像頭之前要先鎖定設備lockForConfiguration 修改完閃光模式之后在解鎖設備unlockForConfiguration
//獲取會話
AVCaptureDevice *device = [self activeCamera];
//判斷是否支持閃光燈模式
if ([device isFlashModeSupported:flashMode]) {
//如果支持,則鎖定設備
NSError *error;
if ([device lockForConfiguration:&error]) {
//修改閃光燈模式
device.flashMode = flashMode;
//修改完成,解鎖釋放設備
[device unlockForConfiguration];
}else
{
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
}
}
}
手電筒
一樣要先鎖定設置 設置torchMode模式之后再解鎖設置
AVCaptureDevice *device = [self activeCamera];
if ([device isTorchModeSupported:torchMode]) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.torchMode = torchMode;
[device unlockForConfiguration];
}else
{
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
}
}
}
對焦
手點擊的地方希望攝像頭對焦,這是很常見的需求
需要注意的是 這里的坐標跟手點擊的屏幕坐標是不一樣的需要做一個轉(zhuǎn)化。
幸運的是蘋果給我一個方法可以直接轉(zhuǎn)化 [AVCaptureVideoPreviewLayer captureDevicePointOfInterestForPoint:point] 得到攝像頭的坐標
AVCaptureDevice *device = [self activeCamera];
//是否支持興趣點對焦 & 是否自動對焦模式
if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error;
//鎖定設備準備配置,如果獲得了鎖
if ([device lockForConfiguration:&error]) {
//將focusPointOfInterest屬性設置CGPoint
device.focusPointOfInterest = point;
//focusMode 設置為AVCaptureFocusModeAutoFocus
device.focusMode = AVCaptureFocusModeAutoFocus;
//釋放該鎖定
[device unlockForConfiguration];
}else{
//錯誤時,則返回給錯誤處理代理
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
}
}
}
曝光
相對對焦多了一點是使用kvo監(jiān)聽設備曝光值的改變adjustingExposure,在kvo 中對設備包括后進行鎖定
AVCaptureDevice *device = [self activeCamera];
// AVCaptureExposureModeLocked 鎖定時的狀態(tài)
// AVCaptureExposureModeAutoExpose 自動曝光
// AVCaptureExposureModeContinuousAutoExposure 自動持續(xù)曝光
// AVCaptureExposureModeCustom 自定義曝光模式
AVCaptureExposureMode exposureMode =AVCaptureExposureModeContinuousAutoExposure;//設置曝光方式為自動調(diào)節(jié)曝光到合適值
//判斷是否支持 AVCaptureExposureModeContinuousAutoExposure 模式
if (device.isExposurePointOfInterestSupported && [device isExposureModeSupported:exposureMode]) {
[device isExposureModeSupported:exposureMode];
NSError *error;
//鎖定設備準備配置
if ([device lockForConfiguration:&error])
{
//配置期望值
device.exposurePointOfInterest = point;
device.exposureMode = exposureMode;
//判斷設備是否支持鎖定曝光的模式。
if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {////設備是否支持相關(guān)設置
//添加觀察是考慮到曝光的設置問題,防止設備在還沒有將曝光值設置完畢就操作了其他事件
//支持,則使用kvo確定設備的adjustingExposure屬性的狀態(tài)。
[device addObserver:self forKeyPath:@"adjustingExposure" options:NSKeyValueObservingOptionNew context:&CameraAdjustingExposureContext];
}
//釋放該鎖定
[device unlockForConfiguration];
}else
{ if(self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])
[self.delegate captureFailedWithError:error];
}
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
//判斷context(上下文)是否為CameraAdjustingExposureContext
if (context == &CameraAdjustingExposureContext) {
//獲取device
AVCaptureDevice *device = (AVCaptureDevice *)object;
//判斷設備是否不再調(diào)整曝光等級,確認設備的exposureMode是否可以設置為AVCaptureExposureModeLocked
//當曝光已經(jīng)不再設置和設備已經(jīng)鎖定了當前的曝光值,在進行相關(guān)操作
if(!device.isAdjustingExposure && [device isExposureModeSupported:AVCaptureExposureModeLocked])
{
//移除作為adjustingExposure 的self,就不會得到后續(xù)變更的通知
[object removeObserver:self forKeyPath:@"adjustingExposure" context:&CameraAdjustingExposureContext];
//異步方式調(diào)回主隊列,
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
if ([device lockForConfiguration:&error]) {
//修改exposureMode
device.exposureMode = AVCaptureExposureModeLocked;
//釋放該鎖定
[device unlockForConfiguration];
}else
{
if ((self.delegate && [self.delegate respondsToSelector :@selector(captureFailedWithError:)])) {
[self.delegate captureFailedWithError:error];
}
}
});
}
}else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
好了。至此大體的功能我們都自己完成了,當然對于音視頻方面,這個只是第一個小步,后續(xù)視頻編碼,音頻編碼,H264編碼和解碼渲染,人臉識別等等處理還有很多,后續(xù)有時間我會繼續(xù)整理。這次代碼我也放到github 上供大家下載 https://github.com/yuchen88888/AVcapture