void ChangeCamera ()
{
MetadataObjectTypesButton.Enabled = false;
SessionPresetsButton.Enabled = false;
CameraButton.Enabled = false;
ZoomSlider.Enabled = false;
// Remove the metadata overlay layers, if any.
RemoveMetadataObjectOverlayLayers ();
DispatchQueue.MainQueue.DispatchAsync (() => {
var currentVideoDevice = videoDeviceInput.Device;
var currentPosition = currentVideoDevice.Position;
var preferredPosition = AVCaptureDevicePosition.Unspecified;
switch (currentPosition) {
case AVCaptureDevicePosition.Unspecified:
case AVCaptureDevicePosition.Front:
preferredPosition = AVCaptureDevicePosition.Back;
break;
case AVCaptureDevicePosition.Back:
preferredPosition = AVCaptureDevicePosition.Front;
break;
}
var videoDevice = DeviceWithMediaType (AVMediaType.Video, preferredPosition);
if (videoDevice != null) {
NSError err;
var vDeviceInput = AVCaptureDeviceInput.FromDevice (videoDevice, out err);
if (err != null) {
Console.WriteLine ($"Error occured while creating video device input: {err}");
return;
}
session.BeginConfiguration ();
// Remove the existing device input first, since using the front and back camera simultaneously is not supported.
session.RemoveInput (videoDeviceInput);
// When changing devices, a session preset that may be supported
// on one device may not be supported by another. To allow the
// user to successfully switch devices, we must save the previous
// session preset, set the default session preset (High), and
// attempt to restore it after the new video device has been
// added. For example, the 4K session preset is only supported
// by the back device on the iPhone 6s and iPhone 6s Plus. As a
// result, the session will not let us add a video device that
// does not support the current session preset.
var previousSessionPreset = session.SessionPreset;
session.SessionPreset = AVCaptureSession.PresetHigh;
if (session.CanAddInput (vDeviceInput)) {
session.AddInput (vDeviceInput);
videoDeviceInput = vDeviceInput;
} else {
session.AddInput (videoDeviceInput);
}
// Restore the previous session preset if we can.
if (session.CanSetSessionPreset (previousSessionPreset))
session.SessionPreset = previousSessionPreset;
session.CommitConfiguration ();
}
MetadataObjectTypesButton.Enabled = true;
SessionPresetsButton.Enabled = true;
CameraButton.Enabled = true;
ZoomSlider.Enabled = true;
ZoomSlider.MaxValue = (float)NMath.Min (videoDeviceInput.Device.ActiveFormat.VideoMaxZoomFactor, 8);
ZoomSlider.Value = (float)videoDeviceInput.Device.VideoZoomFactor;
});
}