void ChangeCamera (UIButton cameraButton)
{
cameraButton.Enabled = false;
RecordButton.Enabled = false;
PhotoButton.Enabled = false;
LivePhotoModeButton.Enabled = false;
CaptureModeControl.Enabled = false;
sessionQueue.DispatchAsync (() => {
AVCaptureDevice currentVideoDevice = videoDeviceInput.Device;
AVCaptureDevicePosition currentPosition = currentVideoDevice.Position;
AVCaptureDevicePosition preferredPosition = 0;
AVCaptureDeviceType preferredDeviceType = 0;
switch (currentPosition) {
case AVCaptureDevicePosition.Unspecified:
case AVCaptureDevicePosition.Front:
preferredPosition = AVCaptureDevicePosition.Back;
preferredDeviceType = AVCaptureDeviceType.BuiltInDuoCamera;
break;
case AVCaptureDevicePosition.Back:
preferredPosition = AVCaptureDevicePosition.Front;
preferredDeviceType = AVCaptureDeviceType.BuiltInWideAngleCamera;
break;
}
var devices = videoDeviceDiscoverySession.Devices;
AVCaptureDevice newVideoDevice = null;
// First, look for a device with both the preferred position and device type. Otherwise, look for a device with only the preferred position.
newVideoDevice = devices.FirstOrDefault (d => d.Position == preferredPosition && d.DeviceType == preferredDeviceType)
?? devices.FirstOrDefault (d => d.Position == preferredPosition);
if (newVideoDevice != null) {
NSError error;
var input = AVCaptureDeviceInput.FromDevice (newVideoDevice, out error);
if (error == null) {
session.BeginConfiguration ();
// Remove the existing device input first, since using the front and back camera simultaneously is not supported.
session.RemoveInput (videoDeviceInput);
if (session.CanAddInput (input)) {
subjectSubscriber?.Dispose ();
subjectSubscriber = NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureDevice.SubjectAreaDidChangeNotification, SubjectAreaDidChange, input.Device);
session.AddInput (input);
videoDeviceInput = input;
} else {
session.AddInput (videoDeviceInput);
}
var connection = MovieFileOutput?.ConnectionFromMediaType (AVMediaType.Video);
if (connection != null) {
if (connection.SupportsVideoStabilization)
connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto;
}
// Set Live Photo capture enabled if it is supported.When changing cameras, the
// IsLivePhotoCaptureEnabled property of the AVCapturePhotoOutput gets set to false when
// a video device is disconnected from the session.After the new video device is
// added to the session, re - enable Live Photo capture on the AVCapturePhotoOutput if it is supported.
photoOutput.IsLivePhotoCaptureEnabled = photoOutput.IsLivePhotoCaptureSupported;
session.CommitConfiguration ();
}
}
DispatchQueue.MainQueue.DispatchAsync (() => {
CameraButton.Enabled = true;
RecordButton.Enabled = MovieFileOutput != null;
PhotoButton.Enabled = true;
LivePhotoModeButton.Enabled = true;
CaptureModeControl.Enabled = true;
});
});
}