我试图切换此代码以使用前置摄像头

时间:2014-12-24 15:02:44

标签: ios iphone

我是编程新手,并尝试修复此代码以使用前置摄像头而不是默认为背面。我不确定我需要改变什么才能使其正常工作。

以下是我的示例代码:

-(void)viewWillAppear:(BOOL)animated{
session = [[AVCaptureSession alloc] init];
[session setSessionPreset:AVCaptureSessionPresetPhoto];

AVCaptureDevice *inputDevice = [AVCaptureDevice       defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];

if ([session canAddInput:deviceInput]) {
    [session addInput:deviceInput];
}

AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc]  initWithSession:session];
                [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
                                            CALayer *rootLayer = [[self view] layer];
                                            [rootLayer setMasksToBounds:YES];
                                            CGRect frame = self.frameForCapture.frame;

[previewLayer setFrame:frame];

[rootLayer insertSublayer:previewLayer atIndex:0];


stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];

[session addOutput:stillImageOutput];

[session startRunning];

1 个答案:

答案 0 :(得分:1)

替换它:

AVCaptureDevice *inputDevice = [AVCaptureDevice       defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];

有了这个:

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *frontCamera;
for (AVCaptureDevice *dev in devices) {
    if (dev.position == AVCaptureDevicePositionFront) {
        frontCamera = dev;
        break;
    }
}
if (!frontCamera) {
    NSLog(@"No front camera found!");
    // Handle no front camera error
}
NSError *error;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];