#pragma warning restore CS4014 private void SetupLiveCameraStream() { captureSession = new AVCaptureSession(); var viewLayer = CameraFeedView.Layer; videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession) { Frame = CameraFeedView.Frame, VideoGravity = AVLayerVideoGravity.ResizeAspectFill }; CameraFeedView.Layer.AddSublayer(videoPreviewLayer); AVCaptureDevice captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); ConfigureCameraForDevice(captureDevice); captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice); captureSession.AddInput(captureDeviceInput); if (isMovie) { // Add audio var audioDevice = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Audio); var audioDeviceInput = AVCaptureDeviceInput.FromDevice(audioDevice, out NSError audioErr); if (audioErr != null) { Console.WriteLine("Couldn't create audio device input: " + audioErr.LocalizedDescription); } if (captureSession.CanAddInput(audioDeviceInput)) { captureSession.AddInput(audioDeviceInput); } else { Console.WriteLine("Couldn't add audio input to session"); } movieOutput = new AVCaptureMovieFileOutput(); captureSession.AddOutput(movieOutput); captureSession.SessionPreset = AVCaptureSession.Preset1280x720; var connection = movieOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection != null && connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } captureSession.CommitConfiguration(); } else { stillImageOutput = new AVCapturePhotoOutput(); stillImageOutput.IsHighResolutionCaptureEnabled = true; stillImageOutput.IsLivePhotoCaptureEnabled = false; captureSession.AddOutput(stillImageOutput); captureSession.CommitConfiguration(); } ShutterButton.Hidden = false; captureSession.StartRunning(); }
public SessionSetupResult ConfigureSession(AVCaptureSession session) { var inputDeviceConfigureResult = _videoDeviceInputManager.ConfigureVideoDeviceInput(session); if (inputDeviceConfigureResult != SessionSetupResult.Success) { return(inputDeviceConfigureResult); } // Add movie file output. Console.WriteLine("capture session: configuring - adding movie file input"); var movieFileOutput = new AVCaptureMovieFileOutput(); if (session.CanAddOutput(movieFileOutput)) { session.AddOutput(movieFileOutput); _videoFileOutput = movieFileOutput; DispatchQueue.MainQueue.DispatchAsync(() => { _videoRecordingDelegate?.DidBecomeReadyForVideoRecording(this); }); } else { Console.WriteLine("capture session: could not add video output to the session"); return(SessionSetupResult.ConfigurationFailed); } _audioCaptureSession = new AudioCaptureSession(); _audioCaptureSession.ConfigureSession(session); return(SessionSetupResult.Success); }
/// <summary> /// Start camera preview /// </summary> public override void StartCamera() { if (Session == null) { Session = new AVCaptureSession(); Device = Configuration.ShowBackCameraFirst ? AVCaptureDevice.Devices.FirstOrDefault(d => d.Position == AVCaptureDevicePosition.Back) : AVCaptureDevice.Devices.FirstOrDefault(d => d.Position == AVCaptureDevicePosition.Front); if (Device == null) { NoCameraAvailable(); Console.WriteLine("Could not find capture device, does your device have a camera?"); return; } try { NSError error; VideoInput = new AVCaptureDeviceInput(Device, out error); Session.AddInput(VideoInput); _videoOutput = new AVCaptureMovieFileOutput { MinFreeDiskSpaceLimit = 1024 * 1024 }; if (Session.CanAddOutput(_videoOutput)) { Session.AddOutput(_videoOutput); } if (Configuration.RecordAudio) { var audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio); _audioInput = new AVCaptureDeviceInput(audioDevice, out error); if (Session.CanAddInput(_audioInput)) { Session.AddInput(_audioInput); } } if (Configuration.DetectFaces) { SetupFaceDetection(); } SetupVideoPreviewLayer(); Session.StartRunning(); } catch { /* ignore */ } FlashConfiguration(true); } base.StartCamera(); }
private void SetupLiveCameraStream() { captureSession = new AVCaptureSession(); captureSession.SessionPreset = AVCaptureSession.PresetMedium; videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession) { Frame = new CGRect(0f, 0f, View.Bounds.Width, View.Bounds.Height), Orientation = GetCameraForOrientation() }; liveCameraStream.Layer.AddSublayer(videoPreviewLayer); var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); ConfigureCameraForDevice(captureDevice); captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice); aVCaptureMovieFileOutput = new AVCaptureMovieFileOutput(); var audioDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Audio); var audioDeviceInput = AVCaptureDeviceInput.FromDevice(audioDevice); captureSession.AddOutput(aVCaptureMovieFileOutput); captureSession.AddInput(captureDeviceInput); captureSession.AddInput(audioDeviceInput); aVCaptureMovieFileOutput.ConnectionFromMediaType(AVMediaType.Video).VideoOrientation = GetCameraForOrientation(); captureSession.StartRunning(); }
private AVCaptureMovieFileOutput _getMovieOutput() { var shouldReinitializeMovieOutput = movieOutput == null; if (!shouldReinitializeMovieOutput) { var connection = movieOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection != null) { shouldReinitializeMovieOutput = shouldReinitializeMovieOutput || !connection.Active; } } if (shouldReinitializeMovieOutput) { movieOutput = new AVCaptureMovieFileOutput(); movieOutput.MovieFragmentInterval = CMTime.Invalid; captureSession.BeginConfiguration(); captureSession.AddOutput(movieOutput); captureSession.CommitConfiguration(); } return(movieOutput); }
void ToggleCaptureMode() { if (CaptureModeControl.SelectedSegment == (int)CaptureMode.Photo) { RecordButton.Enabled = false; sessionQueue.DispatchAsync(() => { // Remove the AVCaptureMovieFileOutput from the session because movie recording is // not supported with AVCaptureSessionPresetPhoto. Additionally, Live Photo // capture is not supported when an AVCaptureMovieFileOutput is connected to the session. session.BeginConfiguration(); session.RemoveOutput(MovieFileOutput); session.SessionPreset = AVCaptureSession.PresetPhoto; session.CommitConfiguration(); MovieFileOutput = null; if (photoOutput.IsLivePhotoCaptureSupported) { photoOutput.IsLivePhotoCaptureEnabled = true; DispatchQueue.MainQueue.DispatchAsync(() => { LivePhotoModeButton.Enabled = true; LivePhotoModeButton.Hidden = false; }); } }); } else if (CaptureModeControl.SelectedSegment == (int)CaptureMode.Movie) { LivePhotoModeButton.Hidden = true; sessionQueue.DispatchAsync(() => { var output = new AVCaptureMovieFileOutput(); if (session.CanAddOutput(output)) { session.BeginConfiguration(); session.AddOutput(output); session.SessionPreset = AVCaptureSession.PresetHigh; var connection = output.ConnectionFromMediaType(AVMediaType.Video); if (connection != null) { if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } session.CommitConfiguration(); MovieFileOutput = output; DispatchQueue.MainQueue.DispatchAsync(() => { RecordButton.Enabled = true; }); } }); } }
public void stopAndRemoveCaptureSession() { stopCaptureSession(); _cameraDevice = CameraDevice.Back; cameraIsSetup = false; previewLayer = null; captureSession = null; // frontCameraDevice = null; // backCameraDevice = null; // mic = null; stillImageOutput = null; movieOutput = null; embeddingView = null; }
private void _setupOutputs() { if (stillImageOutput == null) { stillImageOutput = new AVCaptureStillImageOutput(); } if (movieOutput == null) { movieOutput = new AVCaptureMovieFileOutput(); movieOutput.MovieFragmentInterval = CMTime.Invalid; } if (library == null) { library = new ALAssetsLibrary(); } }
// UIPaintCodeButton takePhotoButton; // UIPaintCodeButton cancelPhotoButton; //protected override async void OnElementChanged(ElementChangedEventArgs<View> e) //{ // base.OnElementChanged(e); // SetupUserInterface(); // SetupEventHandlers(); // await AuthorizeCameraUse(); // SetupLiveCameraStream(); //} public override async void ViewDidLoad() { base.ViewDidLoad(); long totalSeconds = 10000; Int32 preferredTimeScale = 30; CMTime maxDuration = new CMTime(totalSeconds, preferredTimeScale); output = new AVCaptureMovieFileOutput(); //output.MinFreeDiskSpaceLimit = 1024 * 1024; // output.MaxRecordedDuration = maxDuration; SetupUserInterface(); SetupEventHandlers(); await AuthorizeCameraUse(); SetupLiveCameraStream(); }
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); }
private bool addMovieFileOutput(out string errorMessage) { errorMessage = ""; // create a movie file output and add it to the capture session movieFileOutput = new AVCaptureMovieFileOutput(); if (movieSegmentDurationInMilliSeconds > 0) { movieFileOutput.MaxRecordedDuration = new CMTime(movieSegmentDurationInMilliSeconds, 1000); } // setup the delegate that handles the writing movieSegmentWriter = new MovieSegmentWriterDelegate(); // subscribe to the delegate events movieSegmentWriter.MovieSegmentRecordingStarted += new EventHandler <MovieSegmentRecordingStartedEventArgs>(handleMovieSegmentRecordingStarted); movieSegmentWriter.MovieSegmentRecordingComplete += new EventHandler <MovieSegmentRecordingCompleteEventArgs>(handleMovieSegmentRecordingComplete); movieSegmentWriter.CaptureError += new EventHandler <CaptureErrorEventArgs>(handleMovieCaptureError); session.AddOutput(movieFileOutput); return(true); }
public async override void ViewDidLoad() { base.ViewDidLoad(); // Disable UI. The UI is enabled if and only if the session starts running. CameraButton.Enabled = false; RecordButton.Enabled = false; StillButton.Enabled = false; // Create the AVCaptureSession. Session = new AVCaptureSession(); // Setup the preview view. PreviewView.Session = Session; // Communicate with the session and other session objects on this queue. SessionQueue = new DispatchQueue("session queue"); SetupResult = AVCamSetupResult.Success; // Check video authorization status. Video access is required and audio access is optional. // If audio access is denied, audio is not recorded during movie recording. switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video)) { // The user has previously granted access to the camera. case AVAuthorizationStatus.Authorized: break; // The user has not yet been presented with the option to grant video access. // We suspend the session queue to delay session setup until the access request has completed to avoid // asking the user for audio access if video access is denied. // Note that audio access will be implicitly requested when we create an AVCaptureDeviceInput for audio during session setup. case AVAuthorizationStatus.NotDetermined: SessionQueue.Suspend(); var granted = await AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video); if (!granted) { SetupResult = AVCamSetupResult.CameraNotAuthorized; } SessionQueue.Resume(); break; // The user has previously denied access. default: SetupResult = AVCamSetupResult.CameraNotAuthorized; break; } // Setup the capture session. // In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time. // Why not do all of this on the main queue? // Because AVCaptureSession.StartRunning is a blocking call which can take a long time. We dispatch session setup to the sessionQueue // so that the main queue isn't blocked, which keeps the UI responsive. SessionQueue.DispatchAsync(() => { if (SetupResult != AVCamSetupResult.Success) { return; } backgroundRecordingID = -1; NSError error; AVCaptureDevice videoDevice = CreateDevice(AVMediaType.Video, AVCaptureDevicePosition.Back); AVCaptureDeviceInput videoDeviceInput = AVCaptureDeviceInput.FromDevice(videoDevice, out error); if (videoDeviceInput == null) { Console.WriteLine("Could not create video device input: {0}", error); } Session.BeginConfiguration(); if (Session.CanAddInput(videoDeviceInput)) { Session.AddInput(VideoDeviceInput = videoDeviceInput); DispatchQueue.MainQueue.DispatchAsync(() => { // Why are we dispatching this to the main queue? // Because AVCaptureVideoPreviewLayer is the backing layer for PreviewView and UIView // can only be manipulated on the main thread. // Note: As an exception to the above rule, it is not necessary to serialize video orientation changes // on the AVCaptureVideoPreviewLayer’s connection with other session manipulation. // Use the status bar orientation as the initial video orientation. Subsequent orientation changes are handled by // ViewWillTransitionToSize method. UIInterfaceOrientation statusBarOrientation = UIApplication.SharedApplication.StatusBarOrientation; AVCaptureVideoOrientation initialVideoOrientation = AVCaptureVideoOrientation.Portrait; if (statusBarOrientation != UIInterfaceOrientation.Unknown) { initialVideoOrientation = (AVCaptureVideoOrientation)(long)statusBarOrientation; } var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; previewLayer.Connection.VideoOrientation = initialVideoOrientation; }); } else { Console.WriteLine("Could not add video device input to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } AVCaptureDevice audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio); AVCaptureDeviceInput audioDeviceInput = AVCaptureDeviceInput.FromDevice(audioDevice, out error); if (audioDeviceInput == null) { Console.WriteLine("Could not create audio device input: {0}", error); } if (Session.CanAddInput(audioDeviceInput)) { Session.AddInput(audioDeviceInput); } else { Console.WriteLine("Could not add audio device input to the session"); } var movieFileOutput = new AVCaptureMovieFileOutput(); if (Session.CanAddOutput(movieFileOutput)) { Session.AddOutput(MovieFileOutput = movieFileOutput); AVCaptureConnection connection = movieFileOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } else { Console.WriteLine("Could not add movie file output to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } var stillImageOutput = new AVCaptureStillImageOutput(); if (Session.CanAddOutput(stillImageOutput)) { stillImageOutput.CompressedVideoSetting = new AVVideoSettingsCompressed { Codec = AVVideoCodec.JPEG }; Session.AddOutput(StillImageOutput = stillImageOutput); } else { Console.WriteLine("Could not add still image output to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } Session.CommitConfiguration(); }); }
protected void Initialize() { // configure the capture session for medium resolution, change this if your code // can cope with more data or volume CaptureSession = new AVCaptureSession { SessionPreset = AVCaptureSession.PresetMedium }; previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession) { Frame = Bounds, VideoGravity = AVLayerVideoGravity.ResizeAspectFill }; var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back; var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition); if (device == null) { return; } // SET to slow motion NSError error; var input = new AVCaptureDeviceInput(device, out error); movieFileOutput = new AVCaptureMovieFileOutput { //set max record time to 10 minutes MaxRecordedDuration = CMTime.FromSeconds(600, 1) }; photoFileOutput = new AVCapturePhotoOutput(); photoFileOutput.IsHighResolutionCaptureEnabled = true; if (CaptureSession.CanAddOutput(movieFileOutput)) { CaptureSession.BeginConfiguration(); CaptureSession.AddOutput(movieFileOutput); CaptureSession.AddOutput(photoFileOutput); var ranges = device.ActiveFormat.VideoSupportedFrameRateRanges; if (device.LockForConfiguration(out error)) { device.ActiveVideoMinFrameDuration = new CMTime(1, (int)ranges.First().MinFrameRate); device.ActiveVideoMaxFrameDuration = new CMTime(1, (int)ranges.First().MaxFrameRate); } var connection = movieFileOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection != null) { if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } CaptureSession.CommitConfiguration(); } CaptureSession.AddInput(input); Layer.AddSublayer(previewLayer); CaptureSession.StartRunning(); // set frame rate if Slow-mo is requested if (speedOptions == SpeedOptions.SlowMo) { foreach (var vFormat in device.Formats) { var _ranges = vFormat.VideoSupportedFrameRateRanges as AVFrameRateRange[]; var frameRates = _ranges[0]; if (frameRates.MaxFrameRate >= 240.0) { device.LockForConfiguration(out NSError _error); if (_error is null) { device.ActiveFormat = vFormat as AVCaptureDeviceFormat; device.ActiveVideoMinFrameDuration = frameRates.MinFrameDuration; device.ActiveVideoMaxFrameDuration = frameRates.MaxFrameDuration; device.UnlockForConfiguration(); break; } } } } IsPreviewing = true; }
void ToggleCaptureMode(UISegmentedControl captureModeControl) { if (captureModeControl.SelectedSegment == (int)AVCamCaptureMode.Photo) { //RecordButton.Enabled = false; sessionQueue.DispatchAsync(() => { /* * Remove the AVCaptureMovieFileOutput from the session because movie recording is * not supported with AVCaptureSessionPresetPhoto. Additionally, Live Photo * capture is not supported when an AVCaptureMovieFileOutput is connected to the session. */ session.BeginConfiguration(); session.RemoveOutput(movieFileOutput); session.SessionPreset = AVCaptureSession.PresetPhoto; session.CommitConfiguration(); movieFileOutput = null; if (photoOutput.IsLivePhotoCaptureSupported) { photoOutput.IsLivePhotoCaptureEnabled = true; //DispatchQueue.MainQueue.DispatchAsync(() => //{ // LivePhotoModeButton.Enabled = true; // LivePhotoModeButton.Hidden = false; //}); } //if (photoOutput.IsDepthDataDeliverySupported()) //{ // photoOutput.IsDepthDataDeliveryEnabled(true); // DispatchQueue.MainQueue.DispatchAsync(() => // { // DepthDataDeliveryButton.Hidden = false; // DepthDataDeliveryButton.Enabled = true; // }); //} }); } else if (captureModeControl.SelectedSegment == (int)AVCamCaptureMode.Movie) { //LivePhotoModeButton.Hidden = true; //DepthDataDeliveryButton.Hidden = true; sessionQueue.DispatchAsync(() => { var lMovieFileOutput = new AVCaptureMovieFileOutput(); if (session.CanAddOutput(lMovieFileOutput)) { session.BeginConfiguration(); session.AddOutput(lMovieFileOutput); session.SessionPreset = AVCaptureSession.PresetHigh; var connection = lMovieFileOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } session.CommitConfiguration(); movieFileOutput = lMovieFileOutput; //DispatchQueue.MainQueue.DispatchAsync(() => //{ // RecordButton.Enabled = true; //}); } }); } }
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); }
private bool addMovieFileOutput( out string errorMessage ) { errorMessage = ""; // create a movie file output and add it to the capture session movieFileOutput = new AVCaptureMovieFileOutput(); if ( movieSegmentDurationInMilliSeconds > 0 ) { movieFileOutput.MaxRecordedDuration = new CMTime( movieSegmentDurationInMilliSeconds, 1000 ); } // setup the delegate that handles the writing movieSegmentWriter = new MovieSegmentWriterDelegate(); // subscribe to the delegate events movieSegmentWriter.MovieSegmentRecordingStarted += new EventHandler<MovieSegmentRecordingStartedEventArgs>( handleMovieSegmentRecordingStarted ); movieSegmentWriter.MovieSegmentRecordingComplete += new EventHandler<MovieSegmentRecordingCompleteEventArgs>( handleMovieSegmentRecordingComplete ); movieSegmentWriter.CaptureError += new EventHandler<CaptureErrorEventArgs>( handleMovieCaptureError ); session.AddOutput (movieFileOutput); return true; }
public Task <OperationResult> Setup(bool enableAudioRecording, bool enableStillImageCapture = false, UIInterfaceOrientation orientation = UIInterfaceOrientation.Portrait, int numberOfCameras = 1) { TaskCompletionSource <OperationResult> tcs = new TaskCompletionSource <OperationResult>(); var warnings = new List <string>(); NumberOfCameras = numberOfCameras; _enableAudioRecording = enableAudioRecording; _enableStillImageCapture = enableStillImageCapture; _session = new AVCaptureSession(); _backgroundRecordingID = -1; NSError error; var result = AVCaptureDeviceFactory.CreateDevice(AVMediaType.Video, AVCaptureDevicePosition.Back); if (!result.IsSuccessful) { _setupResult = CameraSetupResult.SessionConfigurationFailed; tcs.SetResult(OperationResult.AsFailure("No video devices found, probably running in the simulator")); return(tcs.Task); } _videoDeviceInput = AVCaptureDeviceInput.FromDevice(result.Result, out error); if (_videoDeviceInput == null) { _setupResult = CameraSetupResult.SessionConfigurationFailed; tcs.SetResult(OperationResult.AsFailure(@"Could not create video device input: {error}")); return(tcs.Task); } _session.BeginConfiguration(); if (_session.CanAddInput(_videoDeviceInput)) { _session.AddInput(_videoDeviceInput); var initialVideoOrientation = (AVCaptureVideoOrientation)(long)orientation; PreviewLayer.Session = _session; PreviewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; PreviewLayer.Connection.VideoOrientation = initialVideoOrientation; } else { _setupResult = CameraSetupResult.SessionConfigurationFailed; tcs.SetResult(OperationResult.AsFailure("Could not add video device input to the session")); return(tcs.Task); } if (_enableAudioRecording) { AVCaptureDevice audioDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Audio); AVCaptureDeviceInput audioDeviceInput = AVCaptureDeviceInput.FromDevice(audioDevice, out error); if (audioDeviceInput == null) { warnings.Add(@"Could not create audio device input: {error}"); } else { if (_session.CanAddInput(audioDeviceInput)) { _session.AddInput(audioDeviceInput); } else { warnings.Add("Could not add audio device input to the session"); } } } _movieFileOutput = new AVCaptureMovieFileOutput(); if (_session.CanAddOutput(_movieFileOutput)) { _session.AddOutput(_movieFileOutput); AVCaptureConnection connection = _movieFileOutput.ConnectionFromMediaType(AVMediaType.Video); if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } else { warnings.Add("Could not add movie file output to the session"); _setupResult = CameraSetupResult.SessionConfigurationFailed; } if (_enableStillImageCapture) { _stillImageOutput = new AVCaptureStillImageOutput(); if (_session.CanAddOutput(_stillImageOutput)) { _stillImageOutput.CompressedVideoSetting = new AVVideoSettingsCompressed { Codec = AVVideoCodec.JPEG }; _session.AddOutput(_stillImageOutput); } else { warnings.Add("Could not add still image output to the session"); _setupResult = CameraSetupResult.SessionConfigurationFailed; } } _session.CommitConfiguration(); _setupResult = CameraSetupResult.Success; tcs.SetResult(OperationResult.AsSuccess(string.Empty, warnings)); AddObservers(); return(tcs.Task); }
void ToggleCaptureMode (UISegmentedControl captureModeControl) { if (captureModeControl.SelectedSegment == (int)CaptureMode.Photo) { RecordButton.Enabled = false; sessionQueue.DispatchAsync (() => { // Remove the AVCaptureMovieFileOutput from the session because movie recording is // not supported with AVCaptureSessionPresetPhoto. Additionally, Live Photo // capture is not supported when an AVCaptureMovieFileOutput is connected to the session. session.BeginConfiguration (); session.RemoveOutput (MovieFileOutput); session.SessionPreset = AVCaptureSession.PresetPhoto; session.CommitConfiguration (); MovieFileOutput = null; if (photoOutput.IsLivePhotoCaptureSupported) { photoOutput.IsLivePhotoCaptureEnabled = true; DispatchQueue.MainQueue.DispatchAsync (() => { LivePhotoModeButton.Enabled = true; LivePhotoModeButton.Hidden = false; }); } }); } else if (captureModeControl.SelectedSegment == (int)CaptureMode.Movie) { LivePhotoModeButton.Hidden = true; sessionQueue.DispatchAsync (() => { var output = new AVCaptureMovieFileOutput (); if (session.CanAddOutput (output)) { session.BeginConfiguration (); session.AddOutput (output); session.SessionPreset = AVCaptureSession.PresetHigh; var connection = output.ConnectionFromMediaType (AVMediaType.Video); if (connection != null) { if (connection.SupportsVideoStabilization) connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } session.CommitConfiguration (); MovieFileOutput = output; DispatchQueue.MainQueue.DispatchAsync (() => { RecordButton.Enabled = true; }); } }); } }
private void InitCamera() { //ADD DEVICE INPUTS try { //If no camera avaiable, return if (!IsCameraAvailable) { return; } //Set up a new AV capture session session = new AVCaptureSession(); //Set up a new session //add video capture device var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); AVCaptureDevicePosition cameraPosition = (CameraOption == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back; var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition); //Get the first device where the camera matches the requested camera if (device == null) { //use the default camera if front isn't available device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); } if (device == null) { return; //No device available } 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) { return; } //Set up preview layer (shows what the input device sees) previewlayer = new AVCaptureVideoPreviewLayer(session); previewlayer.Frame = Bounds; if (OrientationOption == OrientationOptions.Landscape) { //landscape previewlayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight; //Video is recoreded upside down but oriented correctly for right handed people //previewlayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; //VIdeo recorded portrait, face to left //previewlayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft; } else { //portrait previewlayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; } 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); } //Resolutions available @ http://stackoverflow.com/questions/19422322/method-to-find-devices-camera-resolution-ios session.SessionPreset = AVCaptureSession.PresetHigh; //Widescreen (Medium is 4:3) Layer.AddSublayer(previewlayer); //session.StartRunning(); //Moved this to StartPreviewing }
public override void ViewDidLoad() { base.ViewDidLoad(); weAreRecording = false; lblError.Hidden = true; btnStartRecording.SetTitle("Start Recording", UIControlState.Normal); //Set up session session = new AVCaptureSession(); //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 UIView cameraView = new UIView(); 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.PresetMedium; Console.WriteLine("About to start running session"); session.StartRunning(); //toggle recording button was pushed. btnStartRecording.TouchUpInside += startStopPushed; //Console.ReadLine (); }
private void configureOutput() { 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.PresetMedium; //configure output location var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var library = System.IO.Path.Combine (documents, "..", "Library"); videoPath = System.IO.Path.Combine (library, "sweetMovieFilm.mov"); videoLocation = new NSUrl (videoPath, false); session.StartRunning (); this.btnRecord.TouchUpInside += startStopPushed; }
void ChangeCaptureMode (UISegmentedControl captureModeControl) { if (captureModeControl.SelectedSegment == (int)CaptureMode.Photo) { RecordButton.Enabled = false; // Remove the AVCaptureMovieFileOutput from the session because movie recording is not supported with AVCaptureSessionPresetPhoto. Additionally, Live Photo // capture is not supported when an AVCaptureMovieFileOutput is connected to the session. sessionQueue.DispatchAsync (() => { Session.BeginConfiguration (); Session.RemoveOutput (movieFileOutput); Session.SessionPreset = AVCaptureSession.PresetPhoto; Session.CommitConfiguration (); movieFileOutput = null; }); } else if (captureModeControl.SelectedSegment == (int)CaptureMode.Movie) { sessionQueue.DispatchAsync (() => { var mfo = new AVCaptureMovieFileOutput (); if (Session.CanAddOutput (mfo)) { Session.BeginConfiguration (); Session.AddOutput (mfo); Session.SessionPreset = AVCaptureSession.PresetHigh; AVCaptureConnection connection = mfo.ConnectionFromMediaType (AVMediaType.Video); if (connection.SupportsVideoStabilization) connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; Session.CommitConfiguration (); movieFileOutput = mfo; DispatchQueue.MainQueue.DispatchAsync (() => { RecordButton.Enabled = true; }); } }); } }
public async override void ViewDidLoad () { base.ViewDidLoad (); // Disable UI. The UI is enabled if and only if the session starts running. CameraButton.Enabled = false; RecordButton.Enabled = false; StillButton.Enabled = false; // Create the AVCaptureSession. Session = new AVCaptureSession (); // Setup the preview view. PreviewView.Session = Session; // Communicate with the session and other session objects on this queue. SessionQueue = new DispatchQueue ("session queue"); SetupResult = AVCamSetupResult.Success; // Check video authorization status. Video access is required and audio access is optional. // If audio access is denied, audio is not recorded during movie recording. switch (AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video)) { // The user has previously granted access to the camera. case AVAuthorizationStatus.Authorized: break; // The user has not yet been presented with the option to grant video access. // We suspend the session queue to delay session setup until the access request has completed to avoid // asking the user for audio access if video access is denied. // Note that audio access will be implicitly requested when we create an AVCaptureDeviceInput for audio during session setup. case AVAuthorizationStatus.NotDetermined: SessionQueue.Suspend (); var granted = await AVCaptureDevice.RequestAccessForMediaTypeAsync (AVMediaType.Video); if (!granted) SetupResult = AVCamSetupResult.CameraNotAuthorized; SessionQueue.Resume (); break; // The user has previously denied access. default: SetupResult = AVCamSetupResult.CameraNotAuthorized; break; } // Setup the capture session. // In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time. // Why not do all of this on the main queue? // Because AVCaptureSession.StartRunning is a blocking call which can take a long time. We dispatch session setup to the sessionQueue // so that the main queue isn't blocked, which keeps the UI responsive. SessionQueue.DispatchAsync (() => { if (SetupResult != AVCamSetupResult.Success) return; backgroundRecordingID = -1; NSError error; AVCaptureDevice videoDevice = CreateDevice (AVMediaType.Video, AVCaptureDevicePosition.Back); AVCaptureDeviceInput videoDeviceInput = AVCaptureDeviceInput.FromDevice (videoDevice, out error); if (videoDeviceInput == null) Console.WriteLine ("Could not create video device input: {0}", error); Session.BeginConfiguration (); if (Session.CanAddInput (videoDeviceInput)) { Session.AddInput (VideoDeviceInput = videoDeviceInput); DispatchQueue.MainQueue.DispatchAsync (() => { // Why are we dispatching this to the main queue? // Because AVCaptureVideoPreviewLayer is the backing layer for PreviewView and UIView // can only be manipulated on the main thread. // Note: As an exception to the above rule, it is not necessary to serialize video orientation changes // on the AVCaptureVideoPreviewLayer’s connection with other session manipulation. // Use the status bar orientation as the initial video orientation. Subsequent orientation changes are handled by // ViewWillTransitionToSize method. UIInterfaceOrientation statusBarOrientation = UIApplication.SharedApplication.StatusBarOrientation; AVCaptureVideoOrientation initialVideoOrientation = AVCaptureVideoOrientation.Portrait; if (statusBarOrientation != UIInterfaceOrientation.Unknown) initialVideoOrientation = (AVCaptureVideoOrientation)(long)statusBarOrientation; var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; previewLayer.Connection.VideoOrientation = initialVideoOrientation; }); } else { Console.WriteLine ("Could not add video device input to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } AVCaptureDevice audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Audio); AVCaptureDeviceInput audioDeviceInput = AVCaptureDeviceInput.FromDevice (audioDevice, out error); if (audioDeviceInput == null) Console.WriteLine ("Could not create audio device input: {0}", error); if (Session.CanAddInput (audioDeviceInput)) Session.AddInput (audioDeviceInput); else Console.WriteLine ("Could not add audio device input to the session"); var movieFileOutput = new AVCaptureMovieFileOutput (); if (Session.CanAddOutput (movieFileOutput)) { Session.AddOutput (MovieFileOutput = movieFileOutput); AVCaptureConnection connection = movieFileOutput.ConnectionFromMediaType (AVMediaType.Video); if (connection.SupportsVideoStabilization) connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } else { Console.WriteLine ("Could not add movie file output to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } var stillImageOutput = new AVCaptureStillImageOutput (); if (Session.CanAddOutput (stillImageOutput)) { stillImageOutput.CompressedVideoSetting = new AVVideoSettingsCompressed { Codec = AVVideoCodec.JPEG }; Session.AddOutput (StillImageOutput = stillImageOutput); } else { Console.WriteLine ("Could not add still image output to the session"); SetupResult = AVCamSetupResult.SessionConfigurationFailed; } Session.CommitConfiguration (); }); }
public override void ViewDidLoad() { base.ViewDidLoad (); weAreRecording = false; lblError.Hidden = true; btnStartRecording.SetTitle("Start Recording", UIControlState.Normal); //Set up session session = new AVCaptureSession (); //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 UIView cameraView = new UIView (); 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.PresetMedium; Console.WriteLine ("About to start running session"); session.StartRunning (); //toggle recording button was pushed. btnStartRecording.TouchUpInside += startStopPushed; //Console.ReadLine (); }
bool AddMovieFileOutput (out string errorMessage) { errorMessage = string.Empty; // create a movie file output and add it to the capture session movieFileOutput = new AVCaptureMovieFileOutput(); if (movieSegmentDurationInMilliSeconds > 0) movieFileOutput.MaxRecordedDuration = new CMTime( movieSegmentDurationInMilliSeconds, 1000); // setup the delegate that handles the writing movieSegmentWriter = new MovieSegmentWriterDelegate(); // subscribe to the delegate events movieSegmentWriter.MovieSegmentRecordingStarted += HandleMovieSegmentRecordingStarted; movieSegmentWriter.MovieSegmentRecordingComplete += HandleMovieSegmentRecordingComplete; movieSegmentWriter.CaptureError += HandleMovieCaptureError; session.AddOutput (movieFileOutput); return true; }