protected override void Dispose(bool disposing) { if (captureDeviceInput != null && captureSession != null) { captureSession.RemoveInput(captureDeviceInput); } if (captureDeviceInput != null) { captureDeviceInput.Dispose(); captureDeviceInput = null; } if (captureSession != null) { captureSession.StopRunning(); captureSession.Dispose(); captureSession = null; } if (stillImageOutput != null) { stillImageOutput.Dispose(); stillImageOutput = null; } base.Dispose(disposing); }
public override void ViewWillDisappear(bool animated) { if (session == null) { } else { if (session.Running == true) { session.StopRunning(); session.RemoveInput(input); session.RemoveInput(audioInput); } } this.btnStartRecording.TouchUpInside -= startStopPushed; foreach (var view in this.View.Subviews) { view.RemoveFromSuperview(); } base.ViewWillDisappear(animated); }
public void ToggleFrontBackCamera() { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; toggleCameraButton.SetBackgroundImage(frontCameraIcon, UIControlState.Normal); } else { devicePosition = AVCaptureDevicePosition.Front; toggleCameraButton.SetBackgroundImage(rearCameraIcon, UIControlState.Normal); } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
public void ToggleFrontBackCamera() { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; isSelfie = false; } else { devicePosition = AVCaptureDevicePosition.Front; isSelfie = true; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
private void HandleRotateCamera() { captureSession.BeginConfiguration(); var currentCameraInput = captureSession.Inputs[0]; captureSession.RemoveInput(currentCameraInput); AVCaptureDevice camera; AVCaptureDeviceInput input = (AVCaptureDeviceInput)currentCameraInput; if (input.Device.Position == AVCaptureDevicePosition.Back) { camera = CameraWithPosition(AVCaptureDevicePosition.Front); } else { camera = CameraWithPosition(AVCaptureDevicePosition.Back); } var videoInput = new AVCaptureDeviceInput(camera, out NSError err); if (err == null) { captureSession.AddInput(videoInput); } captureSession.CommitConfiguration(); AddFlipAnimation(); }
public void StopScanning() { if (stopped) return; Console.WriteLine("Stopping..."); //Try removing all existing outputs prior to closing the session try { while (session.Outputs.Length > 0) session.RemoveOutput (session.Outputs [0]); } catch { } //Try to remove all existing inputs prior to closing the session try { while (session.Inputs.Length > 0) session.RemoveInput (session.Inputs [0]); } catch { } if (session.Running) session.StopRunning(); stopped = true; }
void SwitchCameraType() { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; } else { devicePosition = AVCaptureDevicePosition.Front; } if ((Element.CameraType == CameraType.Front && devicePosition == AVCaptureDevicePosition.Front) || (Element.CameraType == CameraType.Rear && devicePosition == AVCaptureDevicePosition.Back)) { return; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
void UpdateCameraOption() { var devices = AVCaptureDeviceDiscoverySession.Create( new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera, AVCaptureDeviceType.BuiltInDualCamera }, AVMediaType.Video, AVCaptureDevicePosition.Unspecified ); var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back; var device = devices.Devices.FirstOrDefault(d => d.Position == cameraPosition); if (device != null) { var lVideoDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.BeginConfiguration(); // Remove the existing device input first, since using the front and back camera simultaneously is not supported. captureSession.RemoveInput(videoDeviceInput); if (captureSession.CanAddInput(lVideoDeviceInput)) { captureSession.AddInput(lVideoDeviceInput); videoDeviceInput = lVideoDeviceInput; } else { captureSession.AddInput(videoDeviceInput); } captureSession.CommitConfiguration(); } }
public Task SwapCameraAsync() { if (session != null) { var currentCameraInput = session.Inputs[0]; AVCaptureDevice newCamera; if (currentCameraInput.GetPosition() == AVCaptureDevicePosition.Back) { newCamera = AVCaptureDevice .DevicesWithMediaType(AVMediaType.Video) .FirstOrDefault(d => d.Position == AVCaptureDevicePosition.Front); } else { newCamera = AVCaptureDevice .DevicesWithMediaType(AVMediaType.Video) .FirstOrDefault(d => d.Position == AVCaptureDevicePosition.Back); } if (newCamera != null) { session.BeginConfiguration(); session.RemoveInput(currentCameraInput); NSError error = null; var newInput = new AVCaptureDeviceInput(newCamera, out error); if (error == null) { session.AddInput(newInput); CameraPanel = currentCameraInput.GetPosition() == AVCaptureDevicePosition.Back ? CameraPanel.Front : CameraPanel.Back; } else { //rollback session.RemoveInput(currentCameraInput); } session.CommitConfiguration(); } } return(Task.FromResult <object>(null)); }
private void EndSession() { captureSession.StopRunning(); foreach (var i in captureSession.Inputs) { captureSession.RemoveInput(i); } }
protected override void Dispose(bool disposing) { if (disposing) { RemoveObservers(); if (_session != null) { if (_session.Running) { _session.StopRunning(); } PreviewLayer.Session = null; if (_videoDeviceInput != null) { _session.RemoveInput(_videoDeviceInput); _videoDeviceInput.Dispose(); _videoDeviceInput = null; } if (_movieFileOutput != null) { _session.RemoveOutput(_movieFileOutput); _movieFileOutput.Dispose(); _movieFileOutput = null; } if (_stillImageOutput != null) { _session.RemoveOutput(_stillImageOutput); _stillImageOutput.Dispose(); _stillImageOutput = null; } _session.Dispose(); } } base.Dispose(disposing); }
public void StopScanning() { if (overlayView != null) { if (overlayView is ZXingDefaultOverlayView) { (overlayView as ZXingDefaultOverlayView).Destroy(); } overlayView = null; } if (stopped) { return; } Console.WriteLine("Stopping..."); if (outputRecorder != null) { outputRecorder.CancelTokenSource.Cancel(); } //Try removing all existing outputs prior to closing the session try { while (session.Outputs.Length > 0) { session.RemoveOutput(session.Outputs [0]); } } catch { } //Try to remove all existing inputs prior to closing the session try { while (session.Inputs.Length > 0) { session.RemoveInput(session.Inputs [0]); } } catch { } if (session.Running) { session.StopRunning(); } stopped = true; }
public void SetFrontCam() { var devicePosition = AVCaptureDevicePosition.Back; var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
private void ToggleFrontBackCamera(object sender, EventArgs e) { var devicePosition = _captureDeviceInput.Device.Position; devicePosition = devicePosition == AVCaptureDevicePosition.Front ? AVCaptureDevicePosition.Back : AVCaptureDevicePosition.Front; var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); _captureSession.BeginConfiguration(); _captureSession.RemoveInput(_captureDeviceInput); _captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); _captureSession.AddInput(_captureDeviceInput); _captureSession.CommitConfiguration(); }
partial void SwapCamera(UIButton sender) { int currentIndex = devices.FindIndex(d => { return(captureDeviceInput.Device.UniqueID == d.UniqueID); }); currentIndex++; if (currentIndex >= devices.Count) { currentIndex = 0; } AVCaptureDevice device = devices[currentIndex]; captureSession.RemoveInput(captureDeviceInput); ConfigureCameraForDevice(device); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); }
void SetSelectedCamera(CameraSelection selectedCamera) { if (selectedCamera.ToAVCaptureDevicePosition() == _captureDeviceInput.Device.Position) { return; } var device = GetCamera(selectedCamera.ToAVCaptureDevicePosition()); ConfigureCameraForDevice(device); _captureSession.BeginConfiguration(); _captureSession.RemoveInput(_captureDeviceInput); _captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); _captureSession.AddInput(_captureDeviceInput); _captureSession.CommitConfiguration(); }
public void StopScanning() { if (_stopped) { return; } Console.WriteLine("Stopping..."); _outputRecorder?.CancelTokenSource.Cancel(); //Try removing all existing outputs prior to closing the session try { while (_session.Outputs.Length > 0) { _session.RemoveOutput(_session.Outputs[0]); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); } //Try to remove all existing inputs prior to closing the session try { while (_session.Inputs.Length > 0) { _session.RemoveInput(_session.Inputs[0]); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); } if (_session.Running) { _session.StopRunning(); } _stopped = true; }
public ProblemPage() { InitializeComponent(); this.emotionServiceClient = new EmotionServiceClient("MYAPIHERE"); AuthorizeCameraUse(); SetupLiveCameraStream(); var device = GetCameraForOrientation(AVCaptureDevicePosition.Front); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
private bool TryToAddInput(AVCaptureSession session, AVCaptureDeviceInput videoDeviceInput) { if (videoDeviceInput == null) { return(false); } if (_videoDeviceInput != null) { session.RemoveInput(_videoDeviceInput); } if (!session.CanAddInput(videoDeviceInput)) { return(false); } session.AddInput(videoDeviceInput); return(true); }
public SessionSetupResult ConfigureVideoDeviceInput(AVCaptureSession session) { var videoDevice = GetVideoDevice(); if (videoDevice == null) { Console.WriteLine("capture session: could not create capture device"); return(SessionSetupResult.ConfigurationFailed); } var videoDeviceInput = new AVCaptureDeviceInput(videoDevice, out var error); if (error != null) { Console.WriteLine($"Error occured while creating video device input: {error}"); return(SessionSetupResult.ConfigurationFailed); } if (_videoDeviceInput != null) { NSNotificationCenter.DefaultCenter.RemoveObserver(_runtimeErrorNotification); session.RemoveInput(_videoDeviceInput); } if (TryToAddInput(session, videoDeviceInput)) { _videoDeviceInput = videoDeviceInput; } else if (!TryToAddInput(session, _videoDeviceInput)) { return(SessionSetupResult.ConfigurationFailed); } _runtimeErrorNotification = NSNotificationCenter.DefaultCenter.AddObserver( AVCaptureSession.RuntimeErrorNotification, _sessionRuntimeErrorHandler, _videoDeviceInput.Device); return(SessionSetupResult.Success); }
private void _removeMicInput() { if (captureSession == null || captureSession.Inputs == null) { return; } var inputs = captureSession.Inputs; foreach (var input in inputs) { if (input != null) { var deviceInput = input as AVCaptureDeviceInput; if (deviceInput.Device == mic) { captureSession.RemoveInput(input); break; } } } }
partial void SwitchCameraButton_TouchUpInside(UIButton sender) { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; } else { devicePosition = AVCaptureDevicePosition.Front; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
/* * private void PhotoPicked(NSIndexPath indexPath) * { * var collectionCell = (PhotoCollectionViewCell)photoCollection.CellForItem(indexPath); * * if (collectionCell.Asset != null) * { * using (var m = new PHImageManager()) * { * var options = new PHImageRequestOptions(); * * options.DeliveryMode = PHImageRequestOptionsDeliveryMode.FastFormat; * options.Synchronous = false; * options.NetworkAccessAllowed = true; * * m.RequestImageData(collectionCell.Asset, options, (data, dataUti, orientation, info) => * { * if (data != null) * { * var photo = UIImage.LoadFromData(data); * GoToDescription(photo); * } * }); * } * } * }*/ private void SwitchCameraButtonTapped(object sender, EventArgs e) { var devicePosition = _captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; } else { devicePosition = AVCaptureDevicePosition.Front; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); _captureSession.BeginConfiguration(); _captureSession.RemoveInput(_captureDeviceInput); _captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); _captureSession.AddInput(_captureDeviceInput); _captureSession.CommitConfiguration(); }
void BttSwitch_TouchUpInside(object sender, EventArgs e) { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; } else { devicePosition = AVCaptureDevicePosition.Front; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }
void ChangeCamera() { CameraButton.Enabled = false; RecordButton.Enabled = false; PhotoButton.Enabled = false; LivePhotoModeButton.Enabled = false; CaptureModeControl.Enabled = false; sessionQueue.DispatchAsync(() => { var currentVideoDevice = videoDeviceInput.Device; var currentPosition = currentVideoDevice.Position; var preferredPosition = AVCaptureDevicePosition.Unspecified; var preferredDeviceType = AVCaptureDeviceType.BuiltInMicrophone; 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; }); }); }
void ChangeCamera(NSObject sender) { //CameraButton.Enabled = false; //RecordButton.Enabled = false; //PhotoButton.Enabled = false; //LivePhotoModeButton.Enabled = false; //CaptureModeControl.Enabled = false; sessionQueue.DispatchAsync(() => { var currentVideoDevice = videoDeviceInput.Device; var currentPosition = currentVideoDevice.Position; AVCaptureDevicePosition preferredPosition = AVCaptureDevicePosition.Unspecified; AVCaptureDeviceType preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; switch (currentPosition) { //case AVCaptureDevicePosition.Unspecified: //preferredPosition = AVCaptureDevicePosition.Back; //preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; //break; case AVCaptureDevicePosition.Unspecified: case AVCaptureDevicePosition.Front: preferredPosition = AVCaptureDevicePosition.Back; preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; 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. foreach (var device in devices) { if (device.Position == preferredPosition && device.DeviceType.GetConstant() == preferredDeviceType.GetConstant()) { newVideoDevice = device; break; } } // Otherwise, look for a device with only the preferred position. if (newVideoDevice == null) { foreach (var device in devices) { if (device.Position == preferredPosition) { newVideoDevice = device; break; } } } if (newVideoDevice != null) { var lVideoDeviceInput = AVCaptureDeviceInput.FromDevice(newVideoDevice); 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(lVideoDeviceInput)) { if (subjectAreaDidChangeObserver != null) { subjectAreaDidChangeObserver.Dispose(); } subjectAreaDidChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVCaptureDevice.SubjectAreaDidChangeNotification, SubjectAreaDidChange, newVideoDevice); session.AddInput(lVideoDeviceInput); videoDeviceInput = lVideoDeviceInput; } else { session.AddInput(videoDeviceInput); } if (movieFileOutput != null) { var movieFileOutputConnection = movieFileOutput.ConnectionFromMediaType(AVMediaType.Video); if (movieFileOutputConnection.SupportsVideoStabilization) { movieFileOutputConnection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } /* * Set Live Photo capture and depth data delivery if it is supported. When changing cameras, the * `livePhotoCaptureEnabled` and `depthDataDeliveryEnabled` properties of the AVCapturePhotoOutput gets set to NO when * a video device is disconnected from the session. After the new video device is * added to the session, re-enable Live Photo capture and depth data delivery if they are supported. */ photoOutput.IsLivePhotoCaptureEnabled = photoOutput.IsLivePhotoCaptureSupported; //photoOutput.IsDepthDataDeliveryEnabled(photoOutput.IsDepthDataDeliverySupported()); session.CommitConfiguration(); } //DispatchQueue.MainQueue.DispatchAsync(() => //{ // CameraButton.Enabled = true; // RecordButton.Enabled = CaptureModeControl.SelectedSegment == (int)AVCamCaptureMode.Movie; // PhotoButton.Enabled = true; // LivePhotoModeButton.Enabled = true; // CaptureModeControl.Enabled = true; // DepthDataDeliveryButton.Enabled = photoOutput.IsDepthDataDeliveryEnabled(); // DepthDataDeliveryButton.Hidden = !photoOutput.IsDepthDataDeliverySupported(); //}); }); }
private void SetupEventHandlers() { cancelPhotoButton.TouchUpInside += (s, e) => { (Element as CustomVideoCamera).Cancel(); }; videoButton.TouchUpInside += (s, e) => { var element = (Element as CustomVideoCamera); //AssetsLibrary.ALAssetsLibrary li = new // var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // var library = System.IO.Path.Combine(documents, "..", "Library"); var urlpath = System.IO.Path.Combine(Path.GetTempPath(), "sweetMovieFilm.mov"); if (!weAreRecording) { recordTimeTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(0.5), delegate { recordTimeLabel.Text = TimeSpan.FromSeconds(output.RecordedDuration.Seconds).ToString(@"mm\:ss"); //Write Action Here }); NSUrl url = new NSUrl(urlpath, false); NSFileManager manager = new NSFileManager(); NSError error = new NSError(); if (manager.FileExists(urlpath)) { Console.WriteLine("Deleting File"); manager.Remove(urlpath, out error); Console.WriteLine("Deleted File"); } //var dataOutput = new AVCaptureVideoDataOutput() //{ // AlwaysDiscardsLateVideoFrames = true, // WeakVideoSettings = new CVPixelBufferAttributes { PixelFormatType = CVPixelFormatType.CV32BGRA }.Dictionary //}; AVCaptureConnection connection = null; if (output.Connections != null) { foreach (AVCaptureConnection connectionItem in output.Connections) { foreach (AVCaptureInputPort port in connectionItem.InputPorts) { if (port.MediaType == AVMediaType.Video) { connection = connectionItem; break; } } } } if (connection != null && connection.SupportsVideoOrientation) { connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; } //(AVCaptureConnection)output.Connections [0]; if (connection != null) { CustomAvCaptureFileOutPutRecordingDelegate avDel = new CustomAvCaptureFileOutPutRecordingDelegate(); avDel.Element = element; avDel.activityIndicator = activitySpinner; //output.StartRecordingToOutputFile(url, avDel); output.StartRecordingToOutputFile(url, avDel); } Console.WriteLine(urlpath); weAreRecording = true; videoButton.SetImage(UIImage.FromFile(element.StopVideoImage), UIControlState.Normal); } //we were already recording. Stop recording else { activitySpinner.StartAnimating(); output.StopRecording(); videoButton.SetImage(UIImage.FromFile(element.StartVideoImage), UIControlState.Normal); recordTimeLabel.Text = ""; Console.WriteLine("stopped recording"); weAreRecording = false; recordTimeTimer.Invalidate(); } }; flashButton.TouchUpInside += (s, e) => { var element = (Element as CustomVideoCamera); var device = captureDeviceInput.Device; var error = new NSError(); if (device.HasFlash) { if (device.FlashMode == AVCaptureFlashMode.On) { device.LockForConfiguration(out error); device.FlashMode = AVCaptureFlashMode.Off; device.UnlockForConfiguration(); flashButton.SetBackgroundImage(UIImage.FromBundle(element.FlashLightOnImage), UIControlState.Normal); } else { device.LockForConfiguration(out error); device.FlashMode = AVCaptureFlashMode.On; device.UnlockForConfiguration(); flashButton.SetBackgroundImage(UIImage.FromBundle(element.FlashLightOffImage), UIControlState.Normal); } } flashOn = !flashOn; }; photoGallaryButton.TouchUpInside += (s, e) => { var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, MediaTypes = new string[] { "public.movie" } }; imagePicker.AllowsEditing = false; //imagePicker.ShowsCameraControls = false; // imagePicker.ShowsCameraControls = false; //Make sure we have the root view controller which will launch the photo gallery var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } //Show the image gallery vc.PresentViewController(imagePicker, true, null); //call back for when a picture is selected and finished editing imagePicker.FinishedPickingMedia += (sender, e2) => { if (e2.Info[UIImagePickerController.MediaType].ToString() == "public.movie") { NSUrl mediaURL = e2.Info[UIImagePickerController.MediaURL] as NSUrl; if (mediaURL != null) { Console.WriteLine(mediaURL.ToString()); NSData data = NSData.FromUrl(mediaURL); byte[] dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); (Element as CustomVideoCamera).SetPhotoResult(mediaURL.ToString(), dataBytes, 0, 0); } } //UIImage originalImage = e2.Info[UIImagePickerController.OriginalImage] as UIImage; //if (originalImage != null) //{ // //Got the image now, convert it to byte array to send back up to the forms project // var pngImage = originalImage.AsPNG(); // // UIImage imageInfo = new UIImage(pngImage); // byte[] myByteArray = new byte[pngImage.Length]; // System.Runtime.InteropServices.Marshal.Copy(pngImage.Bytes, myByteArray, 0, Convert.ToInt32(pngImage.Length)); // (Element as CustomVideoCamera).SetPhotoResult(originalImage.pmyByteArray, // (int)originalImage.Size.Width, // (int)originalImage.Size.Height); // //System.Runtime.InteropServices.Marshal.Copy(pngImage.Bytes, myByteArray, 0, Convert.ToInt32(pngImage.Length)); // //MessagingCenter.Send<byte[]>(myByteArray, "ImageSelected"); //} //Close the image gallery on the UI thread Device.BeginInvokeOnMainThread(() => { vc.DismissViewController(true, null); }); }; //Cancel button callback from the image gallery imagePicker.Canceled += (sender, e1) => { vc.DismissViewController(true, null); //(Element as CustomCamera).Cancel(); }; //(Element as CustomCamera).Cancel(); }; rotateButton.TouchUpInside += (s, e) => { var devicePosition = captureDeviceInput.Device.Position; if (devicePosition == AVCaptureDevicePosition.Front) { devicePosition = AVCaptureDevicePosition.Back; } else { devicePosition = AVCaptureDevicePosition.Front; } var device = GetCameraForOrientation(devicePosition); ConfigureCameraForDevice(device); captureSession.BeginConfiguration(); captureSession.RemoveInput(captureDeviceInput); captureDeviceInput = AVCaptureDeviceInput.FromDevice(device); captureSession.AddInput(captureDeviceInput); captureSession.CommitConfiguration(); }; }
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; }); }
public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); weAreRecording = false; btnStartRecording = UIButton.FromType(UIButtonType.Custom); btnStartRecording.Frame = new RectangleF(100, 100, 60, 50); btnStartRecording.SetImage(UIImage.FromFile("captureButton.png"), UIControlState.Normal); btnStartRecording.SetTitle("Start Recording", UIControlState.Normal); var screenSize = UIScreen.MainScreen.Bounds; var screenWidth = screenSize.Width; var screenHeight = screenSize.Height; activityIndicator = new UIActivityIndicatorView(); activityIndicator.Frame = new RectangleF(100, 100, 60, 50); activityIndicator.Center = new CGPoint(screenWidth / 2, screenHeight / 2); btnStartRecording.Center = new CGPoint(screenWidth / 2, screenHeight - 40); //Set up session session = new AVCaptureSession(); btnCancelPage = UIButton.FromType(UIButtonType.InfoLight); btnCancelPage.Frame = new RectangleF(200, 200, 160, 150); btnCancelPage.SetImage(UIImage.FromFile("icon_closemap.png"), UIControlState.Normal); btnCancelPage.Center = new CGPoint(15, 30); //Set up inputs and add them to the session //this will only work if using a physical device! Console.WriteLine("getting device inputs"); try { //add video capture device device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); input = AVCaptureDeviceInput.FromDevice(device); session.AddInput(input); //add audio capture device audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio); audioInput = AVCaptureDeviceInput.FromDevice(audioDevice); session.AddInput(audioInput); } catch (Exception ex) { //show the label error. This will always show when running in simulator instead of physical device. //lblError.Hidden = false; return; } //Set up preview layer (shows what the input device sees) Console.WriteLine("setting up preview layer"); previewlayer = new AVCaptureVideoPreviewLayer(session); previewlayer.Frame = this.View.Bounds; //this code makes UI controls sit on top of the preview layer! Allows you to just place the controls in interface builder cameraView = new UIView(); cameraView.Layer.AddSublayer(previewlayer); this.View.AddSubview(cameraView); this.View.SendSubviewToBack(cameraView); Console.WriteLine("Configuring output"); output = new AVCaptureMovieFileOutput(); long totalSeconds = 10000; Int32 preferredTimeScale = 30; CMTime maxDuration = new CMTime(totalSeconds, preferredTimeScale); output.MinFreeDiskSpaceLimit = 1024 * 1024; output.MaxRecordedDuration = maxDuration; if (session.CanAddOutput(output)) { session.AddOutput(output); } session.SessionPreset = AVCaptureSession.Preset640x480; Console.WriteLine("About to start running session"); session.StartRunning(); //toggle recording button was pushed. btnStartRecording.TouchUpInside += startStopPushed; btnCancelPage.TouchUpInside += (s, e) => { (Element as CameraPage).Navigation.PopAsync(); if (session.Running == true) { session.StopRunning(); } //session = null; session.RemoveInput(input); session.RemoveInput(audioInput); session.Dispose(); DismissViewController(true, null); }; View.AddSubview(btnCancelPage); View.AddSubview(btnStartRecording); timerLabel = new UILabel(new RectangleF(50, 50, 50, 50)) { TextColor = UIColor.White }; timerLabel.Text = "00:" + videoLength; timerLabel.Center = new CGPoint(screenWidth / 2, 30); timerLabel.TextColor = UIColor.White; View.AddSubview(timerLabel); }
public void StopScanning() { if (overlayView != null) { if (overlayView is ZXingDefaultOverlayView) { (overlayView as ZXingDefaultOverlayView).Destroy(); } overlayView = null; } if (stopped) { return; } Console.WriteLine("Stopping..."); if (outputRecorder != null) { outputRecorder.CancelTokenSource.Cancel(); } // Revert camera settings to original if (captureDevice != null && captureDevice.LockForConfiguration(out var err)) { captureDevice.FocusMode = captureDeviceOriginalConfig.FocusMode; captureDevice.ExposureMode = captureDeviceOriginalConfig.ExposureMode; captureDevice.WhiteBalanceMode = captureDeviceOriginalConfig.WhiteBalanceMode; if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported) { captureDevice.AutoFocusRangeRestriction = captureDeviceOriginalConfig.AutoFocusRangeRestriction; } if (captureDevice.FocusPointOfInterestSupported) { captureDevice.FocusPointOfInterest = captureDeviceOriginalConfig.FocusPointOfInterest; } if (captureDevice.ExposurePointOfInterestSupported) { captureDevice.ExposurePointOfInterest = captureDeviceOriginalConfig.ExposurePointOfInterest; } if (captureDevice.HasFlash) { captureDevice.FlashMode = captureDeviceOriginalConfig.FlashMode; } if (captureDevice.HasTorch) { captureDevice.TorchMode = captureDeviceOriginalConfig.TorchMode; } captureDevice.UnlockForConfiguration(); } //Try removing all existing outputs prior to closing the session try { while (session.Outputs.Length > 0) { session.RemoveOutput(session.Outputs[0]); } } catch { } //Try to remove all existing inputs prior to closing the session try { while (session.Inputs.Length > 0) { session.RemoveInput(session.Inputs[0]); } } catch { } if (session.Running) { session.StopRunning(); } stopped = true; }