Esempio n. 1
0
        /// <summary>
        /// If there is any recording in progress it will be stopped. - parameter cancel: if true, recorded file will be deleted and corresponding delegate method will be called.
        /// </summary>
        /// <param name="cancel">If set to <c>true</c> cancel.</param>
        public void StopVideoRecording(bool cancel = false)
        {
            if (_videoFileOutput == null)
            {
                Console.WriteLine("capture session: trying to stop a video recording but no movie file output is set");
                return;
            }

            _sessionQueue.DispatchAsync(() =>
            {
                if (_videoFileOutput.Recording == false)
                {
                    Console.WriteLine(
                        "capture session: trying to stop a video recording but no recording is in progress");
                    return;
                }

                if (_videoCaptureDelegate == null)
                {
                    throw new ImagePickerException(
                        "capture session: trying to stop a video recording but video capture delegate is nil");
                }

                _videoCaptureDelegate.IsBeingCancelled = cancel;
                _videoFileOutput.StopRecording();
            });
        }
Esempio n. 2
0
 private void stopMovieWriter()
 {
     if (movieFileOutput == null)
     {
         return;
     }
     movieFileOutput.StopRecording();
 }
Esempio n. 3
0
        void ToggleMovieRecording(NSObject sender)
        {
            /*
             *      Disable the Camera button until recording finishes, and disable
             *      the Record button until recording starts or finishes.
             *
             *      See the AVCaptureFileOutputRecordingDelegate methods.
             */
            //CameraButton.Enabled = false;
            //RecordButton.Enabled = false;
            //CaptureModeControl.Enabled = false;

            /*
             *      Retrieve the video preview layer's video orientation on the main queue
             *      before entering the session queue. We do this to ensure UI elements are
             *      accessed on the main thread and session configuration is done on the session queue.
             */
            var videoPreviewLayerVideoOrientation = VideoPreviewLayer.Connection.VideoOrientation;

            sessionQueue.DispatchAsync(() =>
            {
                if (!movieFileOutput.Recording)
                {
                    if (UIDevice.CurrentDevice.IsMultitaskingSupported)
                    {
                        /*
                         *      Setup background task.
                         *      This is needed because the -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:]
                         *      callback is not received until AVCam returns to the foreground unless you request background execution time.
                         *      This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
                         *      To conclude this background execution, -[endBackgroundTask:] is called in
                         *      -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] after the recorded file has been saved.
                         */
                        backgroundRecordingId = UIApplication.SharedApplication.BeginBackgroundTask(null);
                    }

                    // Update the orientation on the movie file output video connection before starting recording.
                    var movieFileOutputConnection = movieFileOutput.ConnectionFromMediaType(AVMediaType.Video);
                    movieFileOutputConnection.VideoOrientation = videoPreviewLayerVideoOrientation;

                    // Use HEVC codec if supported
                    if (movieFileOutput.AvailableVideoCodecTypes.Where(codec => codec == AVVideo2.CodecHEVC).Any())
                    {
                        movieFileOutput.SetOutputSettings(new NSDictionary(AVVideo.CodecKey, AVVideo2.CodecHEVC), movieFileOutputConnection);
                    }

                    // Start recording to a temporary file.
                    var outputFileName         = Guid.NewGuid().ToString();
                    var livePhotoMovieFilePath = NSFileManager.DefaultManager.GetTemporaryDirectory().Append($"{outputFileName}.mov", false);
                    movieFileOutput.StartRecordingToOutputFile(livePhotoMovieFilePath, this);
                }
                else
                {
                    movieFileOutput.StopRecording();
                }
            });
        }
Esempio n. 4
0
 /**
  * Stop recording a video. Save it to the cameraRoll and give back the url.
  */
 public void stopRecordingVideo(Action <NSUrl, AVCaptureVideoOrientation, NSError> completion)
 {
     if (movieOutput != null)
     {
         if (movieOutput.Recording)
         {
             videoCompletion = completion;
             movieOutput.StopRecording();
         }
     }
 }
Esempio n. 5
0
        private async Task StopRecorddVideo()
        {
            (Element as VideoCameraPage).IsRecording = false;
            aVCaptureMovieFileOutput.StopRecording();
            string filepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string filename = System.IO.Path.Combine(filepath, "video.mp4");

            if (File.Exists(filename))
            {
                byte[] bytes = File.ReadAllBytes(filename);
                (Element as VideoCameraPage).SetPhotoResult(bytes);
                File.Delete(filename);
            }
        }
Esempio n. 6
0
        public Task <OperationResult> StopRecording()
        {
            TaskCompletionSource <OperationResult> tcs = new TaskCompletionSource <OperationResult>();

            if (_movieFileOutput.Recording)
            {
                _movieFileOutput.StopRecording();
                tcs.SetResult(OperationResult.AsSuccess());
            }
            else
            {
                tcs.SetResult(OperationResult.AsFailure("Recording is not in progress"));
            }

            return(tcs.Task);
        }
Esempio n. 7
0
        private void ToggleRecording()
        {
            if (_videoOutput == null)
            {
                return;
            }

            _isRecording = !_isRecording;

            var shotImage = _isRecording ? _videoStopImage : _videoStartImage;

            ShutterButton.SetImage(shotImage, UIControlState.Normal);

            if (_isRecording)
            {
                var outputPath = Path.Combine(Path.GetTempPath(), "output.mov");
                var outputUrl  = NSUrl.FromString("file:///" + outputPath);

                var fileManager = NSFileManager.DefaultManager;
                if (fileManager.FileExists(outputPath))
                {
                    NSError error;
                    fileManager.Remove(outputPath, out error);
                    if (error != null)
                    {
                        Console.WriteLine($"Error removing item at path {outputPath}");
                        _isRecording = false;
                        return;
                    }
                }

                FlipButton.Enabled  = false;
                FlashButton.Enabled = false;
                var connection = _videoOutput.ConnectionFromMediaType(AVMediaType.Video);
                if (connection.SupportsVideoOrientation)
                {
                    connection.VideoOrientation = GetOrientation();
                }
                _videoOutput.StartRecordingToOutputFile(outputUrl, this);
            }
            else
            {
                _videoOutput.StopRecording();
                FlipButton.Enabled  = true;
                FlashButton.Enabled = true;
            }
        }
        public void StopRecording(object sender, EventArgs e)
        {
            if (!XamRecorder.IsRecording)
            {
                throw new Exception("You can't stop recording because it's not started yet.");
            }

            if (IsCameraAvailable)
            {
                output.StopRecording();
            }
            XamRecorder.IsRecording = false;

            var fileSize = NSFileManager.DefaultManager.GetAttributes(XamRecorder.VideoFileName).Size;

            System.Diagnostics.Debug.WriteLine("Video Recorded: {0} ({1} bytes)", XamRecorder.VideoFileName, fileSize);
        }
        partial void TakePhoto(UIButton sender)
        {
            AVCaptureVideoOrientation layerOrientation = videoPreviewLayer.Connection.VideoOrientation;

            if (isMovie)
            {
                ShutterButton.Enabled = false; // disable until recording starts/stops

                if (!movieOutput.Recording)
                {
                    // set up recording
                    if (UIDevice.CurrentDevice.IsMultitaskingSupported)
                    {
                        backgroundRecordingId = UIApplication.SharedApplication.BeginBackgroundTask(null);
                    }

                    AVCaptureConnection connection = movieOutput?.ConnectionFromMediaType(AVMediaType.Video);
                    if (connection != null)
                    {
                        connection.VideoOrientation = layerOrientation;
                    }

                    SetPaths(".mov");

                    movieOutput.StartRecordingToOutputFile(NSUrl.FromFilename(filePath), this);
                }
                else
                {
                    // finish recording
                    movieOutput.StopRecording();
                }
            }
            else
            {
                AVCapturePhotoSettings photoSettings = AVCapturePhotoSettings.Create();

                // The first format in the array is the preferred format
                if (photoSettings.AvailablePreviewPhotoPixelFormatTypes.Length > 0)
                {
                    photoSettings.PreviewPhotoFormat = new NSDictionary <NSString, NSObject>(CVPixelBuffer.PixelFormatTypeKey, photoSettings.AvailablePreviewPhotoPixelFormatTypes[0]);
                }

                stillImageOutput.CapturePhoto(photoSettings, this);
            }
        }
        private void StopRecording()
        {
            timer.Invalidate();
            timer.Dispose();
            timer = null;

            output.StopRecording();

            weAreRecording = false;
            nfloat width  = this.View.Frame.Size.Width;
            nfloat height = this.View.Frame.Size.Height;


            session.StopRunning();
            btnStartRecording.RemoveFromSuperview();
            btnCancelPage.RemoveFromSuperview();

            this.View.AddSubview(activityIndicator);
            activityIndicator.StartAnimating();
        }
Esempio n. 11
0
        void startStopPushed(object sender, EventArgs ea)
        {
            if (!weAreRecording)
            {
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var library   = System.IO.Path.Combine(documents, "..", "Library");
                var urlpath   = System.IO.Path.Combine(library, "sweetMovieFilm.mov");

                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");
                }

                AVCaptureFileOutputRecordingDelegate avDel = new AVCaptureFileOutputRecordingDelegate();
                output.StartRecordingToOutputFile(url, avDel);
                Console.WriteLine(urlpath);
                weAreRecording = true;

                btnStartRecording.SetTitle("Stop Recording", UIControlState.Normal);
            }
            //we were already recording.  Stop recording
            else
            {
                output.StopRecording();

                Console.WriteLine("stopped recording");

                weAreRecording = false;

                btnStartRecording.SetTitle("Start Recording", UIControlState.Normal);
            }
        }
        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();
            };
        }