Skip to content

How To Use The Front Facing Camera With AVCaptureSession

5 months ago

371 words

A number of people have asked how to use the front facing camera for the video preview layer of an AVCaptureSession. First I will give you the code to add/change in the existing AROverlayExample project or the AROverlayImageCaptureExample project and then I will walk you through it.

All you need to do in the sample projects listed above to use the front facing camera is replace the addVideoInput method in the CaptureSessionManager.m file. Here it is:

- (void)addVideoInput {
    NSArray *devices = [AVCaptureDevice devices];
    AVCaptureDevice *frontCamera;
    AVCaptureDevice *backCamera;
    
    for (AVCaptureDevice *device in devices) {
        
        NSLog(@"Device name: %@", [device localizedName]);
        
        if ([device hasMediaType:AVMediaTypeVideo]) {
            
            if ([device position] == AVCaptureDevicePositionBack) {
                NSLog(@"Device position : back");
                backCamera = device;
            }
            else {
                NSLog(@"Device position : front");
                frontCamera = device;
            }
        }
    }
    
    NSError *error = nil;
    AVCaptureDeviceInput *frontFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
    if (!error) {
        if ([[self captureSession] canAddInput:frontFacingCameraDeviceInput])
            [[self captureSession] addInput:frontFacingCameraDeviceInput];
        else {
            NSLog(@"Couldn't add front facing video input");
        }
    }
}

This should be fairly obvious if you read it though but I will spell it out in detail. We start by asking for a list of AVCaptureDevices with:

NSArray *devices = [AVCaptureDevice devices];

Then we make a couple of empty AVCaptureDevices to hold the front and back camera devices. You could just get the one you want but I will show getting both in this example.

AVCaptureDevice *frontCamera;
AVCaptureDevice *backCamera;

Next we iterate through the list of devices and check each one to see if it provides video. If it does provide video it must be one of the cameras. Note, if you use the debugger you will find there are only three devices, the two cameras and the mic.

for (AVCaptureDevice *device in devices) {
...
}

When we have a camera device we then check its position. If it is the back camera we set the place holder we made earlier to be this device. If it is not the back camera it must be the front so we set it to the front camera place holder we made earlier.

Now we have both AVCaptureDeviceInputs and can use which ever one we want to for the session. My example shows using the front camera but you could just as easily use the back camera.

Hope that helps everyone who was wondering about this.

Leave a Reply

Your email address will not be published. Required fields are marked *