短视频从无到有 (一)GPUImage的使用

0.95字数 326阅读 876

前言:本系列文章旨在为刚接触短视频的新人开发提供方便,写的不好的地方,还请各路大神指教。众所周知,开发音视频相关的项目是有很大难度的,基于OpenCV、OpenGL、ffmpeg等众多框架,iOS下又涉及到GPUImage、AVFoundation等框架,语言层面上涉及C、C++语言,可谓非一个人能完成的工作。

正文:

核心思路:使用AVFoundation下的拍摄比较繁琐,而GPUImage封装了这一层,因此我们可以直接使用GPUImage完成拍摄功能。

具体步骤

1.新建工程 在 infoplist文件设置麦克风 相机 相册 图片等权限

<!-- 相册 -->   
<key>NSPhotoLibraryUsageDescription</key>   
<string>App需要您的同意,才能访问相册</string>   
<!-- 相机 -->   
<key>NSCameraUsageDescription</key>   
<string>App需要您的同意,才能访问相机</string>   
<!-- 麦克风 -->   
<key>NSMicrophoneUsageDescription</key>   
<string>App需要您的同意,才能访问麦克风</string>
<!-- 图片 --> 
<key>NSPhotoLibraryAddUsageDescription</key>
<string>App需要您的同意,才能保存图片到您的相册</string>  

2.基于GPUImage 建议用cocoapods导GPUImage,GPUImage引入后,修改以下部分:

 1. GPUImageMovieWriter.h文件中添加isNeedBreakAudioWhiter属性
 
    @property (nonatomic, assign) BOOL isNeedBreakAudioWhiter;
 
  2. GPUImageMovieWriter.m文件中第377行代码修改如下:
    if (CMTIME_IS_INVALID(startTime))
     {
       if (_isNeedBreakAudioWhiter) {
 
 
      }else{
 
      runSynchronouslyOnContextQueue(_movieWriterContext, ^{
      if ((audioInputReadyCallback == NULL) && (assetWriter.status != AVAssetWriterStatusWriting))
    {
       [assetWriter startWriting];
     }
       [assetWriter startSessionAtSourceTime:currentSampleTime];
       startTime = currentSampleTime;
 
     });
         
         }
 
    }
 
3. GPUImageMovieWriter初始化时设置 isNeedBreakAudioWhiter =YES;

3.初始化相机及filterView,filterView是处理美颜的,大家可以处理成不同的美颜效果

//录制相关  AVCaptureSessionPreset1280x720视频分辨率 AVCaptureDevicePositionBack后置摄像头
    videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset1280x720
                                                      cameraPosition:AVCaptureDevicePositionBack];
    
    if ([videoCamera.inputCamera lockForConfiguration:nil]) {
        //自动对焦
        if ([videoCamera.inputCamera isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
            [videoCamera.inputCamera setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
        }
        //自动曝光
        if ([videoCamera.inputCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
            [videoCamera.inputCamera setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
        }
        //自动白平衡
        if ([videoCamera.inputCamera isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
            [videoCamera.inputCamera setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
        }
        
        [videoCamera.inputCamera unlockForConfiguration];
    }
    
    
    //输出方向为竖屏
    videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    //防止允许声音通过的情况下,避免录制第一帧黑屏闪屏
    [videoCamera addAudioInputsAndOutputs];
    videoCamera.horizontallyMirrorFrontFacingCamera = YES;
    videoCamera.horizontallyMirrorRearFacingCamera = NO;

    
    //显示view
    filterView =[[GPUImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:filterView];
    //组合
//    filter = [[GPUImageBilateralFilter alloc] init];
//    [videoCamera addTarget:filter];
//    [filter addTarget:filterView];
    
    
    [videoCamera addTarget:filterView];
     //相机开始运行
    [videoCamera startCameraCapture];

4.初始化moviewriter

  videoURL即视频文件的存储URL
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *videoPath = [[paths objectAtIndex:0] stringByAppendingPathComponent@"tets.MOV"];
   unlink([path UTF8String]);
   videoURL =[NSURL fileURLWithPath:path];
  需要注意的是要调用unlink方法,否则写入可能会失败。
 //写入 
   movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:videoURL size:CGSizeMake(720.0, 1280.0)];
   
   //设置为liveVideo
   movieWriter.isNeedBreakAudioWhiter =YES;
   movieWriter.encodingLiveVideo = YES;
   movieWriter.shouldPassthroughAudio =YES;
   
//  [filter addTarget:movieWriter];
   [videoCamera addTarget:movieWriter];
 //设置声音
   videoCamera.audioEncodingTarget = movieWriter;

5.开始录制与暂停

  开始录制
  [movieWriter startRecording];

  停止录制
  [movieWriter finishRecording];
  [filter removeTarget:movieWriter];
  videoCamera.audioEncodingTarget = nil;

自此,我们就可以完成一个简单的视频录制功能了,下几篇文章我会讲到其中注意事项以及切换前后摄像头、闪光灯、断点拍摄、视频合成等相关功能。

推荐阅读更多精彩内容