AVCaptureSession是AVFoundation的核心類(lèi),用于捕捉視頻和音頻,協(xié)調(diào)視頻和音頻的輸入和輸出流.
- 輸入源
設(shè)備AVCaptureDevice
[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] - 輸出源
添加AVCaptureOutput,即AVCaptureSession的輸出源.一般輸出源分成:音視頻源,圖片源,文件源等.
音視頻輸出AVCaptureAudioDataOutput,AVCaptureVideoDataOutput.
靜態(tài)圖片輸出AVCaptureStillImageOutput(iOS10中被AVCapturePhotoOutput取代了)
AVCaptureMovieFileOutput表示文件源.
創(chuàng)建會(huì)話AVCaptureSession
-(AVCaptureSession *)captureSession{
if (!_captureSession) {
_captureSession = [[AVCaptureSession alloc]init];
if ([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
customLog(@"當(dāng)前使用的是手機(jī)");
}
}
return _captureSession;
}
創(chuàng)建輸入源
1省咨、創(chuàng)建AVCaptureDevice
-(AVCaptureDevice *)getCaptureDevice{
// 每次獲取都要重新創(chuàng)建
NSArray * devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice * device in devices) {
if (device.position == self.captureDevicePosition) {
NSError * error = nil;
if ([device lockForConfiguration:&error]) {
// 焦點(diǎn) 曝光 黑白色 -> 自動(dòng)
if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
}
if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
}
if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
device.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
}
[device unlockForConfiguration];
}
_captureDevice = device;
return _captureDevice;
}
}
return nil;
}
2官边、創(chuàng)建AVCaptureDeviceInput
-(AVCaptureDeviceInput *)getCaptureDeviceInput{
NSError * error = nil;
AVCaptureDevice * device = [self getCaptureDevice];
_captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (error || device == nil) {
NSLog(@"創(chuàng)建失敗: %@",error.description);
}
return _captureDeviceInput;
}
3、添加輸入源到會(huì)話中
AVCaptureSession * session = self.captureSession;
// 添加輸入對(duì)象到會(huì)話
if ([session.inputs containsObject:self.captureDeviceInput]) {
[session removeInput:self.captureDeviceInput];
}
AVCaptureDeviceInput * input = [self getCaptureDeviceInput];
if ([session canAddInput:input]) {
[session addInput:input];
}
創(chuàng)建輸出源并添加到會(huì)話中
// 添加照片輸出
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
AVCapturePhotoOutput * photoOutput = [[AVCapturePhotoOutput alloc]init];
// 先移除
if ([session.outputs containsObject:self.captureOutput]) {
[session removeOutput:self.captureOutput];
}
// 添加
if ([session canAddOutput:photoOutput]) {
[session addOutput:photoOutput];
}
self.captureOutput = photoOutput;
}else{
AVCaptureStillImageOutput * stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
NSDictionary *myOutputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
[stillImageOutput setOutputSettings:myOutputSettings];
// 先移除
if ([session.outputs containsObject:self.captureOutput]) {
[session removeOutput:self.captureOutput];
}
// 添加
if ([session canAddOutput:stillImageOutput]){
[session addOutput:stillImageOutput];
}
self.captureOutput = stillImageOutput;
}
輸出對(duì)象-視頻流對(duì)象作為輸出適合及時(shí)獲取輸出數(shù)據(jù)(直播)
AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
[videoDataOutput setAlwaysDiscardsLateVideoFrames:YES];// 默認(rèn)為YES
// 設(shè)置代理脚粟,捕獲視頻樣品數(shù)據(jù)
// 注意:隊(duì)列必須是串行隊(duì)列,才能獲取到數(shù)據(jù),而且不能為空
dispatch_queue_t photoCaptureQueue = dispatch_queue_create(MDPhotoCaptureQueue, DISPATCH_QUEUE_SERIAL);
[videoDataOutput setSampleBufferDelegate:self queue:photoCaptureQueue];
if ([session canAddOutput:videoDataOutput]) {
[session addOutput:videoDataOutput];
}
#pragma mark AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
- // 及時(shí)獲取視頻輸出數(shù)據(jù)
customLog(@"采集到數(shù)據(jù)");
}
添加預(yù)覽圖層
-(void)addPreviewLayer{
// 視頻預(yù)覽圖層
AVCaptureVideoPreviewLayer *previedLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
previedLayer.frame = [UIScreen mainScreen].bounds;
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer insertSublayer:previedLayer atIndex:0];
_previewLayer = previedLayer;
}
切換前后置攝像頭-切換輸入源
- (void)changeInput{
// 移除輸入對(duì)象
if (self.captureDeviceInput && [self.captureSession.inputs containsObject:self.captureDeviceInput]) {
[self.captureSession removeInput:self.captureDeviceInput];
}
// 添加輸入對(duì)象到會(huì)話
AVCaptureDeviceInput * input = [self getCaptureDeviceInput];
if ([self.captureSession canAddInput:input]) {
[self.captureSession addInput:input];
}
self.isChangeCaptureDevicePostion = NO;
// 給攝像頭的切換添加翻轉(zhuǎn)動(dòng)畫(huà)
CATransition *animation = [CATransition animation];
animation.duration = .5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.type = @"oglFlip";
if (self.captureDevicePosition == AVCaptureDevicePositionFront) {
animation.subtype = kCATransitionFromLeft;
}else{
animation.subtype = kCATransitionFromRight;
}
[self.previewLayer addAnimation:animation forKey:nil];
}
拍照按鈕點(diǎn)擊-獲取圖片
-(void)commitButtonAction{
// 拍照
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
AVCapturePhotoOutput * output = (AVCapturePhotoOutput *)self.captureOutput;
//從 AVCaptureStillImageOutput 中取得 AVCaptureConnection
self.captureConnection = [output connectionWithMediaType:AVMediaTypeVideo];
AVCapturePhotoSettings * settings = [AVCapturePhotoSettings photoSettings];
[output capturePhotoWithSettings:settings delegate:self];
}else{
AVCaptureStillImageOutput * stillImageOutput = (AVCaptureStillImageOutput *)self.captureOutput;
//從 AVCaptureStillImageOutput 中取得 AVCaptureConnection
self.captureConnection = [stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
[stillImageOutput captureStillImageAsynchronouslyFromConnection:self.captureConnection completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
if (imageDataSampleBuffer != nil) {
NSData * data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
// 取得靜態(tài)影像 兩種獲取方式
//UIImage * image = [[UIImage alloc]initWithData:data];
CFDataRef cfData = CFBridgingRetain(data);
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(cfData);
CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dataProvider, nil, YES, kCGRenderingIntentDefault);
CFBridgingRelease(cfData);
// 裁剪圖片
[self cropWithImage:[UIImage imageWithCGImage:cgImage]];
// 取得影像數(shù)據(jù)(需要ImageIO.framework 與 CoreMedia.framework)
CFDictionaryRef attachments = CMGetAttachment(imageDataSampleBuffer, kCGImagePropertyExifDictionary, NULL);
customLog(@"影像屬性: %@", attachments);
}
}];
}
}
代理獲取圖片AVCapturePhotoOutput
#pragma mark AVCapturePhotoCaptureDelegate
// IOS - 11
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
if (error) {
customLog(@"獲取圖片錯(cuò)誤 --- %@",error.localizedDescription);
}
if (photo) {
if (@available(iOS 11.0, *)) {
CGImageRef cgImage = [photo CGImageRepresentation];
UIImage * image = [UIImage imageWithCGImage:cgImage];
customLog(@"獲取圖片成功 --- %@",image);
} else {
customLog(@"不是走這個(gè)代理方法");
}
}
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error{
if (error) {
customLog(@"獲取圖片錯(cuò)誤 --- %@",error.localizedDescription);
}
if (photoSampleBuffer) {
NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
UIImage *image = [UIImage imageWithData:data];
customLog(@"獲取圖片成功 --- %@",image);
}
}