#import "ViewController.h"#import@interface ViewController ()/* 输入设备 摄像头*/@property (strong, nonatomic) AVCaptureDeviceInput *videoInput;/* 输入设备 麦克风 */@property (strong, nonatomic) AVCaptureDeviceInput *audioInput;/* 输出设备 */@property (strong, nonatomic) AVCaptureMovieFileOutput *outPut;/* 会话 */@property (strong, nonatomic) AVCaptureSession *session;/* 预览的图层 */@property (weak, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // 输入设备 摄像头 麦克风 // 摄像头的输入设备 AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:videoDevice error:nil]; // 麦克风的输入设备 AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; self.audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioDevice error:nil]; // 输出设备 self.outPut = [[AVCaptureMovieFileOutput alloc] init]; // 会话 -->链接输入和输出设备 self.session = [[AVCaptureSession alloc] init]; // 添加输入和输出设备 if ([self.session canAddInput:self.videoInput]) { [self.session addInput:self.videoInput]; } if ([self.session canAddInput:self.audioInput]) { [self.session addInput:self.audioInput]; } if ([self.session canAddOutput:self.outPut]) { [self.session addOutput:self.outPut]; } // 预览的图层 AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session]; self.previewLayer = previewLayer; self.previewLayer.frame = self.view.bounds; [self.view.layer addSublayer:previewLayer]; // 开启会话 [self.session startRunning];}- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{
if (self.outPut.isRecording == YES) {
// 停止录制
[self.outPut stopRecording];
}else{
// 文件保存的路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"123.mov"];
// 转换类型
NSURL *url = [NSURL fileURLWithPath:path];
// 开始录制视频 url:视频保存的位置
[self.outPut startRecordingToOutputFileURL:url recordingDelegate:self];
}
}
/// 开始录制视频
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
{
NSLog(@"开始录制视频");
}
/// 录制视频成功
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
NSLog(@"录制视频成功");
}
@end