美文网首页音视频
AVFoundation 视频拍摄基础篇

AVFoundation 视频拍摄基础篇

作者: 陈雨尘 | 来源:发表于2021-02-03 17:37 被阅读0次

    问:你有做过音视频吗?答:做过但是我们是用第三方的。对具体实现不是很清楚。
    如果面试的时候你这么回答那大概率是没有戏的,最近很多公司都有对音视频类的需求,奈何大多数开发者没有具体去研究过。这里我大概整理下iOS 如果自己实现一套视频拍摄工具。

    1.常用的类

    • AVCaptureSession 捕捉绘画
    • 相当于插板的功能承接输入和输出
    • AVCaptureDevice 捕捉设备
    • AVMediaTypeVideo/AVMediaTypeAudio 不能直接给AVCaptureSession 使用 需要借助AVCaptureDeviceInput
    • AVCaptureDeviceInput 源输入
    • AVCaptureVideoPreviewLayer 捕获预览

    AVCaptureOutput 子类

    • AVCaptureAudioDataOutput :一种捕获输出,用于记录音频,并在录制音频时提供对音频样本缓冲区的访问。
    • AVCaptureAudioPreviewOutput :一种捕获输出,与一个核心音频输出设备相关联、可用于播放由捕获会话捕获的音频。
    • AVCaptureDepthDataOutput :在兼容的摄像机设备上记录场景深度信息的捕获输出。
    • AVCaptureMetadataOutput :用于处理捕获会话AVCaptureSession产生的定时元数据的捕获输出。
    • AVCaptureStillImageOutput :在macOS中捕捉静止照片的捕获输出。该类在iOS 10.0中被弃用,并且不支持新的相机捕获功能,例如原始图像输出和实时照片。在iOS 10.0或更高版本中,使用AVCapturePhotoOutput类代替。
    • AVCapturePhotoOutput :静态照片、动态照片和其他摄影工作流的捕获输出。
    • AVCaptureVideoDataOutput :记录视频并提供对视频帧进行处理的捕获输出。
    • AVCaptureFileOutput :用于捕获输出的抽象超类,可将捕获数据记录到文件中。
    • AVCaptureMovieFileOutput :继承自AVCaptureFileOutput,将视频和音频记录到QuickTime电影文件的捕获输出。
    • AVCaptureAudioFileOutput :继承自AVCaptureFileOutput,记录音频并将录制的音频保存到文件的捕获输出。

    大概画了下设置过程他们之前的设置关系如图:


    2.常用的设置方法

    设置AVCaptureSession 设置输入输出源

       //创建捕捉会话。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
        {
            //创建失败
        }
        //选择默认音频捕捉设备 即返回一个内置麦克风
        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
        {
            //创建失败
        }
        //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];
        }
        self.videoQueue = dispatch_queue_create("yc.VideoQueue", NULL);
        //创建成功
    }
    

    开启session

    创建一个线程出去捕捉事件,当然一般来说录制过程是要可见的,所以需要设置session的AVCaptureVideoPreviewLayer,然后将layer贴到你想显示的view上用于捕捉预览

        {
            //使用同步调用会损耗一定的时间,则用异步的方式处理
            dispatch_async(self.videoQueue, ^{
                [self.captureSession startRunning];
            }); 
        }
    

    一切准备就绪就可以开始录制了

            
            //获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性
            AVCaptureConnection * videoConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
            
            //判断是否支持设置videoOrientation 属性。
            if([videoConnection isVideoOrientationSupported])
            {
                //支持则修改当前视频的方向
                videoConnection.videoOrientation = [self currentVideoOrientation];
                
            }
            
            //判断是否支持视频稳定 可以显著提高视频的质量。只会在录制视频文件涉及
            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];
                    }
                }
            }
            
            //查找写入捕捉视频的唯一文件系统URL.
            self.outputURL = [self uniqueURL];
            if (self.outputURL) {
                //在捕捉输出上调用方法 参数1:录制保存路径  参数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回调方法中做对应的处理,比如视频转码,存入相册 等等。

    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
        {
            //创建AVCaptureDeviceInput 出现错误,则通知委托来处理该错误
            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];
                }
            }
            
        }
        
    }
    

    对焦

    手点击的地方希望摄像头对焦,这是很常见的需求
    需要注意的是 这里的坐标跟手点击的屏幕坐标是不一样的需要做一个转化。
    幸运的是苹果给我一个方法可以直接转化 [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监听设备曝光值的改变adjustingExposure,在kvo 中对设备包括后进行锁定

      
        AVCaptureDevice *device = [self activeCamera];
        
        //    AVCaptureExposureModeLocked 锁定时的状态
        //    AVCaptureExposureModeAutoExpose 自动曝光
        //    AVCaptureExposureModeContinuousAutoExposure 自动持续曝光
        //    AVCaptureExposureModeCustom 自定义曝光模式
        
        AVCaptureExposureMode exposureMode =AVCaptureExposureModeContinuousAutoExposure;//设置曝光方式为自动调节曝光到合适值
        
        //判断是否支持 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]) {////设备是否支持相关设置
                    //添加观察是考虑到曝光的设置问题,防止设备在还没有将曝光值设置完毕就操作了其他事件
                    //支持,则使用kvo确定设备的adjustingExposure属性的状态。
                    [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;
            
            //判断设备是否不再调整曝光等级,确认设备的exposureMode是否可以设置为AVCaptureExposureModeLocked
            //当曝光已经不再设置和设备已经锁定了当前的曝光值,在进行相关操作
            if(!device.isAdjustingExposure && [device isExposureModeSupported:AVCaptureExposureModeLocked])
            {
                //移除作为adjustingExposure 的self,就不会得到后续变更的通知
                [object removeObserver:self forKeyPath:@"adjustingExposure" context:&CameraAdjustingExposureContext];
                
                //异步方式调回主队列,
                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];
        }
    }
    

    好了。至此大体的功能我们都自己完成了,当然对于音视频方面,这个只是第一个小步,后续视频编码,音频编码,H264编码和解码渲染,人脸识别等等处理还有很多,后续有时间我会继续整理。这次代码我也放到github 上供大家下载 https://github.com/yuchen88888/AVcapture

    相关文章

      网友评论

        本文标题:AVFoundation 视频拍摄基础篇

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