lxian's Blog

用Avfoundation 录像

参考了Capturing Video on iOS, CUSTOM CAMERA ON IOS – AVCAPTURESESSION, AVCAPTUREVIDEOPREVIEWLAYER TUTORIAL。(吐槽一下Capturing Video on iOS… sample code 搞那么复杂干嘛。。)

先开一个新的AVCaptureSession

1
2
AVCaptureSession *captureSession = [AVCaptureSession new];
[captureSession setSessionPreset:AVCaptureSessionPresetHigh];// the video quiality

然后加入audio 和video inputs

audio

1
2
3
4
5
6
7
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//allow recording and replaying at the same time
[audioSession setActive:YES error:nil];
AVCaptureDeviceInput *micDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio] error:&error];
if ([captureSession canAddInput:micDeviceInput]) {
[captureSession addInput:micDeviceInput];
}

video

1
2
3
4
5
6
7
8
9
10
11
12
13
14
AVCaptureDevice *cameraDevice = nil;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
// make it the front camera
for (AVCaptureDevice *device in devices) {
if ([device position] == AVCaptureDevicePositionFront) {
cameraDevice = device;
}
}
AVCaptureDeviceInput *cameraDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:cameraDevice error:&error];
if ([captureSession canAddInput:cameraDeviceInput]) {
[captureSession addInput:cameraDeviceInput];
}

然后把output也连上

1
2
3
4
AVCaptureMovieFileOutput *movieFileOutput = [AVCaptureMovieFileOutput new];
if([captureSession canAddOutput:movieFileOutput]){
[captureSession addOutput:movieFileOutput];
}

最后再加个显示live preview 的layer

1
2
3
4
5
6
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession];
UIView *camView = [[UIView alloc] initWithFrame:CGRectMake(...)];
previewLayer.frame = camView.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[camView.layer addSublayer:previewLayer];
[self.view addSubview:camView];

开始录像

1
2
3
NSURL *outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@tmp.mov", NSTemporaryDirectory()]];
[captureSession startRunning];
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

结束&保存

1
2
3
[_captureSession stopRunning];
[_movieFileOutput stopRecording];
UISaveVideoAtPathToSavedPhotosAlbum(_movieFileOutput.outputFileURL.path, nil, NULL, NULL);

完🐶