1. 创建视频设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
2. 初始化一个摄像头输入设备
AVCaptureDeviceInput *inputVideo = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
3. 创建麦克风设备
AVCaptureDevice *deviceAudio = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
4. 初始化麦克风输入设备
AVCaptureDeviceInput *inputAudio = [AVCaptureDeviceInput deviceInputWithDevice:deviceAudio error:NULL];
5. 初始化一个movie的文件输出
AVCaptureMovieFileOutput *output = [[AVCaptureMovieFileOutput alloc] init];
//设置录制时间与每秒帧数
Float64 seconds = self.recordTimeout;//录制时间
int32_t frameNumber = 20;//每秒帧数
output.maxRecordedDuration = CMTimeMakeWithSeconds(seconds, frameNumber);
6.初始化一个会话
AVCaptureSession *session = [[AVCaptureSession alloc]init];
//视频录制分辨率
if ([session canSetSessionPreset:AVCaptureSessionPreset640x480]) {
[session setSessionPreset:AVCaptureSessionPreset640x480];
}
7. 将输入输出设备添加到会话中
if ([session canAddInput:inputVideo]) {
[session addInput:inputVideo];
}
if ([session canAddInput:inputAudio]) {
[session addInput:inputAudio];
}
if ([session canAddOutput:output]) {
[session addOutput:output];
}
8. 创建一个预览涂层
AVCaptureVideoPreviewLayer *preLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
// 设置图层的大小
preLayer.frame = self.view.bounds;
preLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:preLayer];
9. 开启会话,准备录制
[session startRunning];
10. 开始录制视频
//设置录制视频保存的路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@”myVidio.mov”];
//转为视频保存的url
NSURL *url = [NSURL fileURLWithPath:path];
//开始录制,并设置控制器为录制的代理
[self.output startRecordingToOutputFileURL:url recordingDelegate:self];
[self.view.layer addSublayer:self.preLayer];
11. 停止录制
[self.output stopRecording];
12. 录制完成代理
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error;
13. 计算文件大小
-(long long) fileSizeAtPath:(NSString *) filePath{
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1024;
}
return 0;
}
githubDemo地址:
播放器 断点续传 视频压缩 视频录制 工程中的RecordSession.h文件