#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController ()<AVCaptureFileOutputRecordingDelegate> @property(nonatomic ,strong) AVCaptureFileOutput * outPut; @property(nonatomic ,strong)AVCaptureSession * session; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //创建输入设备 AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput * inputVideo = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil]; AVCaptureDevice * audio = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; AVCaptureDeviceInput * inpoutAudio = [[AVCaptureDeviceInput alloc]initWithDevice:audio error:nil]; //创建文件输出设备 AVCaptureFileOutput * outPut = [[AVCaptureFileOutput alloc]init]; self.outPut = outPut; //创建会话(加工厂) AVCaptureSession * session = [[AVCaptureSession alloc]init]; self.session = session; //判断设备时候能够添加, 可能设备损坏 if ([session canAddInput:inpoutAudio]) { [session addInput:inpoutAudio]; } if ([session canAddInput:inputVideo]) { [session addInput:inputVideo]; } if ([session canAddOutput:outPut]) { [session addOutput:outPut]; } //创建预览层 AVCaptureVideoPreviewLayer * preViewLayer = [[AVCaptureVideoPreviewLayer alloc]init]; //设置frame preViewLayer.frame = self.view.bounds; //插入到View上 [self.view.layer insertSublayer:preViewLayer atIndex:0]; //开始会话 [session startRunning]; } - (IBAction)recode:(id)sender { if ([self.outPut isRecording]) { [self.outPut stopRecording]; }else{ NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"录制视屏.MP4"]; [self.outPut startRecordingToOutputFileURL:[NSURL fileURLWithPath:path] recordingDelegate:self]; } }
时间: 2024-10-07 12:55:21