iOS技术点iOS 音视频iOS、Swift

iOS 视频录制与储存

2020-05-30  本文已影响0人  ZT_Story

前言

之前都是碎片化的整理遇到的问题和情况,这次因为需求需要,打算系统性的记录一下原生视频录制以及储存的内容

需求

需求要求录制一段问答视频,语音合成问题,让用户回答,最终集合为一条视频

实现

1、原生视频录制

需要注意的准备工作,在info.plist中添加对应的权限询问

Privacy - Camera Usage Description
Privacy - Photo Library Additions Usage Description     // iOS 11 新出的权限,写入相册时需要配置
Privacy - Photo Library Usage Description
Privacy - Microphone Usage Description    // 麦克风

开始视频录制细节
① 创建创建捕捉会话 - AVCaptureSession

- (AVCaptureSession *)captureSession{
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc] init];
        // 画质
        _captureSession.sessionPreset = AVCaptureSessionPresetLow;
        // 添加输入
        if ([_captureSession canAddInput:self.captureDeviceInput]) {
            [_captureSession addInput:self.captureDeviceInput];
        }
        if ([_captureSession canAddInput:self.audioMicInput]) {
            [_captureSession addInput:self.audioMicInput];
        }
        // 添加输出
        if ([_captureSession canAddOutput:self.captureMovieFileOutput]) {
           [_captureSession addOutput:self.captureMovieFileOutput];
        }
    }
    return _captureSession;
}

② 设置视频&音频的输入 - AVCaptureDeviceInput

// 视频输入
-(AVCaptureDevice *)captureDevice{
    if (!_captureDevice) {
        // 设置默认后置摄像头
        _captureDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
    }
    return _captureDevice;
}
- (AVCaptureDeviceInput *)captureDeviceInput{
    if (!_captureDeviceInput) {
        _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:nil];
    }
    return _captureDeviceInput;
}
// 麦克风输入
- (AVCaptureDeviceInput *)audioMicInput {
    if (_audioMicInput == nil) {
        AVCaptureDevice *mic = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        NSError *error;
        _audioMicInput = [AVCaptureDeviceInput deviceInputWithDevice:mic error:&error];
        if (error) {
            // TODO
        }
    }
    return _audioMicInput;
}

③ 设置视频&音频的输出 - AVCaptureMovieFileOutput

- (AVCaptureMovieFileOutput *)captureMovieFileOutput
{
    if(_captureMovieFileOutput == nil)
    {
        _captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc]init];
   }
    return _captureMovieFileOutput;
}

④ 设置添加视频预览层 - AVCaptureVideoPreviewLayer

- (AVCaptureVideoPreviewLayer *)previewLayer{
    if (!_previewLayer) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return _previewLayer;
}

然后在初始化的时候将视频预览层加到view上就可以了

[self.layer insertSublayer:self.previewLayer atIndex:0];

⑤ 开始录制视频

#pragma mark - 开始运行
- (void)startRunning {
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self.captureSession startRunning];
    });
}
#pragma mark - 停止运行
- (void)stopRunning {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self.captureSession stopRunning];
    });
}
#pragma mark - 开始录制
- (void)startCapture {
    if(self.captureMovieFileOutput.isRecording) {
        return;
    }
    NSString *defultPath = [self getVideoPathCache];
    NSString *outputFielPath = [defultPath stringByAppendingPathComponent:[self getVideoNameWithType:@"mp4"]];
    NSLog(@"视频保存地址%@", outputFielPath);
    NSURL *fileUrl = [NSURL fileURLWithPath:outputFielPath];
    // 设置录制视频流输出的路径
    [self.captureMovieFileOutput startRecordingToOutputFileURL:fileUrl recordingDelegate:self];
}
#pragma mark - 停止录制
- (void) stopCapture {
    if ([self.captureMovieFileOutput isRecording]) {
        [self.captureMovieFileOutput stopRecording];
    }
}
2、视频储存

这里内容是上面开始录制部分的补充

#pragma mark - 视频地址
- (NSString *)getVideoPathCache
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * videoCache = [[paths firstObject] stringByAppendingPathComponent:@"videos"];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:videoCache isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) ) {
        [fileManager createDirectoryAtPath:videoCache withIntermediateDirectories:YES attributes:nil error:nil];
    };
    return videoCache;
}
#pragma mark - 拼接视频文件名称
- (NSString *)getVideoNameWithType:(NSString *)fileType
{
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HHmmss"];
    NSDate * NowDate = [NSDate dateWithTimeIntervalSince1970:now];
    NSString * timeStr = [formatter stringFromDate:NowDate];
    NSString *fileName = [NSString stringWithFormat:@"video_%@.%@",timeStr,fileType];
    return fileName;
}

关于视频录制结束的保存

#import <Photos/Photos.h>
// 需要遵循 <AVCaptureFileOutputRecordingDelegate> 协议

#pragma mark - 录制完成回调
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
    // 这里可以将视频按照路径存于沙盒,也可以存到相册方便查看,亦可上传服务器等等
    PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
    [photoLibrary performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:outputFileURL];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"已将视频保存至相册,文件大小:%lld", captureOutput.recordedFileSize);
        } else {
            NSLog(@"未能保存视频到相册");
        }
    }];
}
上一篇下一篇

猜你喜欢

热点阅读