前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >AVFoundation 视频拍摄基础篇

AVFoundation 视频拍摄基础篇

作者头像
陈雨尘
发布2021-02-05 14:32:29
9730
发布2021-02-05 14:32:29
举报
文章被收录于专栏:雨尘分享

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

1.常用的类

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

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

2.常用的设置方法

设置AVCaptureSession 设置输入输出源

代码语言:javascript
复制
   //创建捕捉会话。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上用于捕捉预览

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

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

代码语言:javascript
复制
        //获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性
        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回调方法中做对应的处理,比如视频转码,存入相册 等等。

代码语言:javascript
复制
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
      fromConnections:(NSArray *)connections
                error:(NSError *)error

当然拍摄过程中还会涉及到 切换摄像头,自动曝光,自动对焦等等,下面大概列举一下常用的方法

切换摄像头

session beginConfiguration 做对应摄像头输入然后在commitConfiguration 提交配置

代码语言:javascript
复制
    //判断是否有多个摄像头
    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

代码语言:javascript
复制
    //获取会话
    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模式之后再解锁设置

代码语言:javascript
复制
    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] 得到摄像头的坐标

代码语言:javascript
复制
    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 中对设备包括后进行锁定

代码语言:javascript
复制
    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];
        }
        
        
    }
    
}
代码语言:javascript
复制
- (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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
人脸识别
腾讯云神图·人脸识别(Face Recognition)基于腾讯优图强大的面部分析技术,提供包括人脸检测与分析、比对、搜索、验证、五官定位、活体检测等多种功能,为开发者和企业提供高性能高可用的人脸识别服务。 可应用于在线娱乐、在线身份认证等多种应用场景,充分满足各行业客户的人脸属性识别及用户身份确认等需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档