我试图从ios设备的相机中获取要在屏幕上显示的内容而我不想使用ImagePickerController,因为我希望能够更好地控制其外观在屏幕上查看,我希望能够更好地控制相机的光圈和采样率。
这是我在UIViewController的viewDidLoad方法中使用的代码:
//Setting up the camera
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
//This gets the back camera, which is the default video avcapturedevice
AVCaptureDevice *camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *cameraInput = [AVCaptureDeviceInput deviceInputWithDevice:camera error:&error];
if (cameraInput) {
[captureSession addInput:cameraInput];
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Camera not found" message:@"Your device must have a camera in order to use this feature" delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
UIView* cameraView = [[UIView alloc] initWithFrame:self.view.bounds];
previewLayer.frame = cameraView.bounds;
previewLayer.videoGravity = @"AVLayerVideoGravityResizeAspect";
[cameraView.layer addSublayer:previewLayer];
[self.view addSubview:cameraView];
当视图加载时,屏幕上没有任何内容,我也没有收到错误消息。知道我错过了什么吗?
答案 0 :(得分:5)
您实际上从未在您显示的代码中启动捕获会话:
[captureSession startRunning];
此外,我建议您查看the AVCam sample code that Apple has provided,了解他们如何设置捕获会话和预览图层。它包含一些有关如何管理捕获会话的好提示(它们将所有内容分发到自定义串行队列)。例如,它在代码中包含以下注释:
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive).