美文网首页
AVFoundation 初探之----自定义系统相机

AVFoundation 初探之----自定义系统相机

作者: 小溜子 | 来源:发表于2020-06-13 14:39 被阅读0次

    AVCaptureSession开启捕获任务,配置定制捕获任务的输入源(多种摄像头),通过AVFoundation内各种Data output输出数据(元数据、视频帧、音频帧),AVAssetWriter开启写任务,将音视频数据归档为媒体文件。

    1.初始化相关对象

    首先创建一个UIView作为预览图层,负责显示摄像头当前捕获的的画面

    创建secession

    设置分辨率

    设置输入设备(摄像头、麦克风)

    设置输出(拍照stillImageOutput、录视频MovieFileOutput)

     //创建捕捉会话。AVCaptureSession 是捕捉场景的中心枢纽
        self.captureSession = [[AVCaptureSession alloc]init];
        /*
         AVCaptureSessionPresetHigh
         AVCaptureSessionPresetMedium
         AVCaptureSessionPresetLow
         AVCaptureSessionPreset640x480
         AVCaptureSessionPreset1280x720
         AVCaptureSessionPresetPhoto
         */
        //设置图像的分辨率
        self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
        
        //拿到默认视频捕捉设备 iOS系统返回后置摄像头
        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
        {
            return NO;
        }
        
        //选择默认音频捕捉设备 即返回一个内置麦克风
        AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        
        //为这个设备创建一个捕捉设备输入
        AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:error];
       
        //判断audioInput是否有效
        if (audioInput) {
            
            //canAddInput:测试是否能被添加到会话中
            if ([self.captureSession canAddInput:audioInput])
            {
                //将audioInput 添加到 captureSession中
                [self.captureSession addInput:audioInput];
            }
        }else
        {
            return NO;
        }
    
        //AVCaptureStillImageOutput 实例 从摄像头捕捉静态图片
        self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
        
        //配置字典:希望捕捉到JPEG格式的图片
        self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
        
        //输出连接 判断是否可用,可用则添加到输出连接中去
        if ([self.captureSession canAddOutput:self.imageOutput])
        {
            [self.captureSession addOutput:self.imageOutput];
            
        }
        //创建一个AVCaptureMovieFileOutput 实例,用于将Quick Time 电影录制到文件系统
        self.movieOutput = [[AVCaptureMovieFileOutput alloc]init];
        
        //输出连接 判断是否可用,可用则添加到输出连接中去
        if ([self.captureSession canAddOutput:self.movieOutput])
        {
            [self.captureSession addOutput:self.movieOutput];
        }
    

    2.切换摄像头

    切换摄像头(判断是否有多个摄像头、获取当前设备的方向设备,将设备封装成AVCaptureDeviceInput、标志原配置变化开始、移除原本的输入设备,添加新的输入设备、配置完成后提交配置)

     //判断是否有多个摄像头
        if (![self canSwitchCameras])
        {
            returnNO;
        }
    
        //获取当前设备的反向设备
        NSError*error;
        AVCaptureDevice*videoDevice = [selfinactiveCamera];
        //将输入设备封装成AVCaptureDeviceInput
        AVCaptureDeviceInput*videoInput = [AVCaptureDeviceInputdeviceInputWithDevice:videoDeviceerror:&error];
    
        //判断videoInput 是否为nil
        if(videoInput)
        {
            //标注原配置变化开始
    
            [self.captureSession beginConfiguration];
    
            //将捕捉会话中,原本的捕捉输入设备移除
            [self.captureSession removeInput:self.activeVideoInput];
    
            //判断新的设备是否能加入
            if([self.captureSessioncanAddInput:videoInput])
            {
                //能加入成功,则将videoInput 作为新的视频捕捉设备
                [self.captureSessionaddInput:videoInput];
                //将获得设备 改为 videoInput
                self.activeVideoInput= videoInput;
            }else
            {
                //如果新设备,无法加入。则将原本的视频捕捉设备重新加入到捕捉会话中
                [self.captureSession addInput:self.activeVideoInput];
            }
            //配置完成后, AVCaptureSession commitConfiguration 会分批的将所有变更整合在一起。
            [self.captureSession commitConfiguration];
        }else
        {
            //创建AVCaptureDeviceInput 出现错误,则通知委托来处理该错误
            [self.delegate deviceConfigurationFailedWithError:error];
            returnNO;
        }
    

    3.点击聚焦

    判断当前活跃设备是否支持兴趣点对焦&是否自动对焦模式

    锁定设备准备配置,如果获得锁

    focusPointOfInterest属性设置为用户所点击的point

    focusMode 设置为AVCaptureFocusModeAutoFocus

    释放该锁定

    AVCaptureDevice*device = [selfactiveCamera];
    
        //是否支持兴趣点对焦 & 是否自动对焦模式
        if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            NSError*error;
    
            //锁定设备准备配置,如果获得了锁
            if([devicelockForConfiguration:&error]) {
                //将focusPointOfInterest属性设置CGPoint
                device.focusPointOfInterest= point;
    
                //focusMode 设置为AVCaptureFocusModeAutoFocus
                device.focusMode = AVCaptureFocusModeAutoFocus;
    
                //释放该锁定
                [deviceunlockForConfiguration];
            }else{
    
                //错误时,则返回给错误处理代理
                [self.delegate deviceConfigurationFailedWithError:error];
            }
        }
    

    4.点击曝光

    判断设备是否支持对一个兴趣点进行曝光

    判断是否支持曝光&是否支持继续自动曝光模式

    锁定设备准备配置

    配置期望值

    判断设备是否支持锁定曝光模式

    使用kvo确定设备的adjustingExposure属性状态(调整曝光等级属性)

    释放该锁定

    在kvo回调方法中

    判断context(上下文)是否为THCameraAdjustingExposureContext

    判断设备是否不再调整曝光等级,确认设备的exposureMode是否可以设置为AVCaptureExposureModeLocked

    移除作为adjustingExposure的self,就不会得到后续变更通知

    异步方式回到主队列

    设置闪光灯|手电筒

    获取当前活跃设备

    判断是否支持闪光灯模式|手电筒模式

    锁定设备

    配置对应模式

    释放设备

    
     AVCaptureDevice*device = [selfactiveCamera];
    
        //是否支持兴趣点对焦 & 是否自动对焦模式
        if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            NSError*error;
    
            //锁定设备准备配置,如果获得了锁
            if([devicelockForConfiguration:&error]) {
                //将focusPointOfInterest属性设置CGPoint
                device.focusPointOfInterest= point;
                //focusMode 设置为AVCaptureFocusModeAutoFocus
                device.focusMode = AVCaptureFocusModeAutoFocus;
                //释放该锁定
                [deviceunlockForConfiguration];
            }else{
                //错误时,则返回给错误处理代理
                [self.delegate deviceConfigurationFailedWithError:error];
            }
        }
    

    5.拍照

    通过AVCaptureStillImageOutput 获取连接

    程序只支持纵向,但是如果用户横向拍照时,需要调整结果照片的方向

    判断是否支持设置视频方向

    获取设备当前方向值并设置

    定义一个handler块,会返回1个图片的NDData数据

    捕捉静态图片

    //获取连接
        AVCaptureConnection*connection = [self.imageOutputconnectionWithMediaType:AVMediaTypeVideo];
        //程序只支持纵向,但是如果用户横向拍照时,需要调整结果照片的方向
        //判断是否支持设置视频方向
        if (connection.isVideoOrientationSupported) {
      //获取方向值
            connection.videoOrientation= [selfcurrentVideoOrientation];
        }
        //定义一个handler 块,会返回1个图片的NSData数据
        idhandler = ^(CMSampleBufferRefsampleBuffer,NSError*error)
                    {
                        if(sampleBuffer !=NULL) {
                            NSData*imageData = [AVCaptureStillImageOutputjpegStillImageNSDataRepresentation:sampleBuffer];
                            UIImage*image = [[UIImagealloc]initWithData:imageData];
         //重点:捕捉图片成功后,将图片传递出去
                            [selfwriteImageToAssetsLibrary:image];
                        }else
                        {
                            NSLog(@"NULL sampleBuffer:%@",[errorlocalizedDescription]);
                        }
                    };
        //捕捉静态图片
        [self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:handler];
    

    创建ALAssersLibrary实例 进步保存图片到相册

    成功后,发送捕捉图片通知,用于左下角的缩略图

    6.录视频

    获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性

    判断是否支持设置videoOrientation属性

    修改当前视频方向

    判断是否支持视频稳定,可以显著提高视频的质量,只会在理智视频文件涉及

    摄像头可以进行平滑对焦模式操作,即减慢摄像头镜头对焦速度。当用户移动拍摄时摄像头会尝试快速自动对焦

    在捕捉输出上调用开始录制方法

    使用ALAssersLibraay写入视频到资源库

    成功后,发送捕捉图片通知,用于左下角的缩略图

    //获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性
            AVCaptureConnection* videoConnection = [self.movieOutputconnectionWithMediaType:AVMediaTypeVideo];
            //判断是否支持设置videoOrientation 属性。
    
            if([videoConnectionisVideoOrientationSupported])
            {
                //支持则修改当前视频的方向
                videoConnection.videoOrientation= [selfcurrentVideoOrientation];
            }
     //判断是否支持视频稳定 可以显著提高视频的质量。只会在录制视频文件涉及
            if([videoConnection isVideoStabilizationSupported])
            {
                videoConnection.enablesVideoStabilizationWhenAvailable = YES;
            }
            AVCaptureDevice*device = [selfactiveCamera];
            //摄像头可以进行平滑对焦模式操作。即减慢摄像头镜头对焦速度。当用户移动拍摄时摄像头会尝试快速自动对焦。
            if (device.isSmoothAutoFocusEnabled) {
                NSError*error;
                if([devicelockForConfiguration:&error]) {
                    device.smoothAutoFocusEnabled=YES;
                    [deviceunlockForConfiguration];
                }else
                {
                    [self.delegate deviceConfigurationFailedWithError:error];
                }
            }
            //查找写入捕捉视频的唯一文件系统URL.
             self.outputURL= [selfuniqueURL];
            //在捕捉输出上调用方法 参数1:录制保存路径  参数2:代理
            [self.movieOutput startRecordingToOutputFileURL:self.outputURL recordingDelegate:self];
    

    相关文章

      网友评论

          本文标题:AVFoundation 初探之----自定义系统相机

          本文链接:https://www.haomeiwen.com/subject/usnatktx.html