# iOS实时获取摄像头

需求:

类似微信音视频通话,有个摄像头按钮切换。

实现:

#import "C2RealTimeCameraView.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreVideo/CoreVideo.h>
#import <CoreMedia/CoreMedia.h>

@interface C2RealTimeCameraView() <AVCaptureVideoDataOutputSampleBufferDelegate>

@property (nonatomic, strong) AVCaptureSession *captureSession; // 管理输入输出音视频流
@property (nonatomic, strong) UIImageView *imageView; // 输出图像
// @property (nonatomic, strong) CALayer *customLayer; // 输出图像
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *prevLayer; // 相机预览
@property (nonatomic, strong) dispatch_queue_t sessionQueue;
@end

@implementation C2RealTimeCameraView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = kColorFromRGB(0xEFF0F2);
    }
    return self;
}

- (void)setupCameraWithPosition:(AVCaptureDevicePosition)devicePosition onVideoOrientation:(AVCaptureVideoOrientation)viedoOrientation
{
    if (self.captureSession.running == YES){
        self.imageView.frame = self.bounds;
        self.prevLayer.frame = self.bounds;
        return;
    }
    AVCaptureDevice * testDevice;
    // 创建Camera镜头组,实现镜头自动变焦 AVCaptureDeviceTypeBuiltInMicrophone
    NSArray<AVCaptureDeviceType> * deviceTypeArr = @[AVCaptureDeviceTypeBuiltInWideAngleCamera];
    AVCaptureDeviceDiscoverySession * myDiscoverySesion = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceTypeArr mediaType:AVMediaTypeVideo position:devicePosition];
    
    for (AVCaptureDevice *item in myDiscoverySesion.devices) {
        // 找到对应的摄像头
        if ([item position] == devicePosition) {
            testDevice = item;
            break;
        }
    }
    [self createQueue];
    // 如果没有找到镜头,就不做操作,防止崩溃
    if (testDevice != nil) {

        AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput
                                              deviceInputWithDevice:testDevice  error:nil];
        
        AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
        captureOutput.alwaysDiscardsLateVideoFrames = YES;
        [captureOutput setSampleBufferDelegate:self queue:self.sessionQueue];
        
        NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
        NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
        NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
        [captureOutput setVideoSettings:videoSettings];
        
        self.captureSession = [[AVCaptureSession alloc] init];
        [self.captureSession addInput:captureInput];
        [self.captureSession addOutput:captureOutput];
//        dispatch_async(self.sessionQueue, ^{
//            //开始运行session
//
//        });
//        if (self.captureSession.running == NO){
//            [self sessionStartRunning];
//        }
        // FIXME:用CALayer.contents显示有可能会导致内存溢出,程序崩溃。
//        self.customLayer = [CALayer layer];
//        self.customLayer.frame = self.bounds;
//        self.customLayer.transform = CATransform3DRotate(CATransform3DIdentity, M_PI/1.0f, 0, 0, 1);
//        self.customLayer.affineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI);
//        self.customLayer.contentsGravity = kCAGravityResizeAspect;
//        [self.layer addSublayer:self.customLayer];
        
        // 解决录屏图像问题
        self.imageView = [[UIImageView alloc] init];
        self.imageView.frame = self.bounds;
        [self addSubview:self.imageView];
        
        // 相机预览
        self.prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        self.prevLayer.frame = self.bounds;
        // 指定屏幕方向
        self.prevLayer.connection.videoOrientation = viedoOrientation;
        self.prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.layer addSublayer:self.prevLayer];
    }
}

/**
 *  创建一个队列,防止阻塞主线程
 */
- (void)createQueue{
    dispatch_queue_t sessionQueue = dispatch_queue_create("sessionQueue", DISPATCH_QUEUE_SERIAL);
    self.sessionQueue = sessionQueue;
}

- (void)sessionStartRunning {
    WEAKSELF
    dispatch_async(wkSelf.sessionQueue, ^{
        StrongWeakSelf
        if (!stSelf.captureSession.running) {
            [stSelf.captureSession startRunning];
        }
    });
}

- (void)sessionStopRunning {
    WEAKSELF
    dispatch_async(wkSelf.sessionQueue, ^{
        StrongWeakSelf
        if (stSelf.captureSession.running) {
            [stSelf.captureSession stopRunning];
        }
    });
}

#pragma mark - AVCaptureSession delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    CGImageRef newImage = CGBitmapContextCreateImage(newContext);
    CGContextRelease(newContext);
    CGColorSpaceRelease(colorSpace);
    
    // 执行此方法有可能会导致内存飙升,程序崩溃。
//    [self.customLayer performSelectorOnMainThread:@selector(setContents:) withObject: (__bridge id) newImage waitUntilDone:YES];
    
    // 新图层的输出图像方向
    UIImage * image = [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationDown];
    CGImageRelease(newImage);
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
}

@end

注意事项:

1、创建的时候调用[self.cameraView setupCameraWithPosition:AVCaptureDevicePositionFront onVideoOrientation:AVCaptureVideoOrientationPortrait];方法初始化;

2、点击按钮切换的时候调用sessionStartRunning和sessionStopRunning方法即可。

3、sessionStartRunning切换展示画面会白一下,暂时没找到好的解决办法;

4、不要点击切换才调setupCameraWithPosition方法,某些机型会卡很久才出现摄像头画面;

5、注意多线程和回到主线程处理。

参考链接:

https://www.jianshu.com/p/36fff4ffef47

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,333评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,812评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,016评论 0 246
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,293评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,650评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,788评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,003评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,741评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,462评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,681评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,168评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,528评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,169评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,119评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,846评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,719评论 2 274

推荐阅读更多精彩内容