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 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;
		}
示例#3
0
        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 ();
			});
		}
		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;
		}