// 捕獲音視頻
- (void)setupCaputureVideo
{
// 1.創建捕獲會話,必須要強引用,否則會被釋放
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
_captureSession = captureSession;
// 2.獲取攝像頭設備,默認是后置攝像頭
AVCaptureDevice *videoDevice = [self getVideoDevice:AVCaptureDevicePositionFront];
// 3.獲取聲音設備
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
// 4.創建對應視頻設備輸入對象
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
_currentVideoDeviceInput = videoDeviceInput;
// 5.創建對應音頻設備輸入對象
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
// 6.添加到會話中
// 注意“最好要判斷是否能添加輸入,會話不能添加空的
// 6.1 添加視頻
if ([captureSession canAddInput:videoDeviceInput]) {
[captureSession addInput:videoDeviceInput];
}
// 6.2 添加音頻
if ([captureSession canAddInput:audioDeviceInput]) {
[captureSession addInput:audioDeviceInput];
}
// 7.獲取視頻數據輸出設備
AVCaptureVideoDataOutput *videoOutput = [[AVCaptureVideoDataOutput alloc] init];
// 7.1 設置代理,捕獲視頻樣品數據
// 注意:隊列必須是串行隊列,才能獲取到數據,而且不能為空
dispatch_queue_t videoQueue = dispatch_queue_create("Video Capture Queue", DISPATCH_QUEUE_SERIAL);
[videoOutput setSampleBufferDelegate:self queue:videoQueue];
if ([captureSession canAddOutput:videoOutput]) {
[captureSession addOutput:videoOutput];
}
// 8.獲取音頻數據輸出設備
AVCaptureAudioDataOutput *audioOutput = [[AVCaptureAudioDataOutput alloc] init];
// 8.2 設置代理,捕獲視頻樣品數據
// 注意:隊列必須是串行隊列,才能獲取到數據,而且不能為空
dispatch_queue_t audioQueue = dispatch_queue_create("Audio Capture Queue", DISPATCH_QUEUE_SERIAL);
[audioOutput setSampleBufferDelegate:self queue:audioQueue];
if ([captureSession canAddOutput:audioOutput]) {
[captureSession addOutput:audioOutput];
}
// 9.獲取視頻輸入與輸出連接,用于分辨音視頻數據
_videoConnection = [videoOutput connectionWithMediaType:AVMediaTypeVideo];
// 10.添加視頻預覽圖層
AVCaptureVideoPreviewLayer *previedLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
previedLayer.frame = [UIScreen mainScreen].bounds;
[self.view.layer insertSublayer:previedLayer atIndex:0];
_previedLayer = previedLayer;
// 11.啟動會話
[captureSession startRunning];
}
// 指定攝像頭方向獲取攝像頭
- (AVCaptureDevice *)getVideoDevice:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if (device.position == position) {
return device;
}
}
return nil;
}
#pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
// 獲取輸入設備數據,有可能是音頻有可能是視頻
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
if (_videoConnection == connection) {
NSLog(@"采集到視頻數據");
} else {
NSLog(@"采集到音頻數據");
}
}