Exemplo n.º 1
0
        public Task <OperationResult> StartRecording(string filePath)
        {
            TaskCompletionSource <OperationResult> tcs = new TaskCompletionSource <OperationResult>();

            if (_movieFileOutput.Recording)
            {
                tcs.SetResult(OperationResult.AsFailure("Recording already in progress"));
            }
            else
            {
                if (UIDevice.CurrentDevice.IsMultitaskingSupported)
                {
                    // Setup background task. This is needed because the IAVCaptureFileOutputRecordingDelegate.FinishedRecording
                    // 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, UIApplication.SharedApplication.EndBackgroundTask is called in
                    // IAVCaptureFileOutputRecordingDelegate.FinishedRecording 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.
                AVCaptureConnection connection = _movieFileOutput.ConnectionFromMediaType(AVMediaType.Video);
                connection.VideoOrientation = PreviewLayer.Connection.VideoOrientation;

                // Turn OFF flash for video recording.
                _videoDeviceInput.Device.SetFlashMode(AVCaptureFlashMode.Off);

                // Start recording to a temporary file.
                _movieFileOutput.StartRecordingToOutputFile(new NSUrl(filePath, false), this);

                tcs.SetResult(OperationResult.AsSuccess());
            }

            return(tcs.Task);
        }
        void startStopPushed(object sender, EventArgs ea)
        {
            if (!weAreRecording)
            {
                var screenSize   = UIScreen.MainScreen.Bounds;
                var screenWidth  = screenSize.Width;
                var screenHeight = screenSize.Height;

                var time = 16;

                timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1.0), delegate {
                    time -= 1;
                    if (time >= 10)
                    {
                        timerLabel.Text = "00:" + time.ToString();
                    }
                    else
                    {
                        timerLabel.Text = "00:0" + time.ToString();
                    }

                    if (time == 0)
                    {
                        StopRecording();
                    }
                });

                timer.Fire();

                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var library   = System.IO.Path.Combine(documents, "..", "Library");
                var urlpath   = System.IO.Path.Combine(library, "Report.mov");

                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 MyRecordingDelegate(cameraView, this, Element);
                output.StartRecordingToOutputFile(url, avDel);
                Console.WriteLine(urlpath);
                weAreRecording = true;
                btnStartRecording.SetImage(UIImage.FromFile("captureButton_red.png"), UIControlState.Normal);
                timer.Fire();
                View.AddSubview(timerLabel);
            }
            //we were already recording.  Stop recording
            else
            {
                StopRecording();
            }
        }
Exemplo n.º 3
0
        private async Task RecordVideo()
        {
            var basePath       = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var outputFilePath = Path.Combine(basePath, Path.ChangeExtension("video", "mp4"));

            (Element as VideoCameraPage).IsRecording = true;
            aVCaptureMovieFileOutput.StartRecordingToOutputFile(NSUrl.FromFilename(outputFilePath), this);
        }
Exemplo n.º 4
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();
                }
            });
        }
Exemplo n.º 5
0
        private void startRecordingNextMovieFilename()
        {
            // generate file name
            currentSegmentFile = System.IO.Path.Combine(this.movieRecordingDirectory, string.Format("video_{0}.mov", nextMovieIndex++));
            NSUrl segmentUrl = NSUrl.FromFilename(currentSegmentFile);

            // start recording
            movieFileOutput.StartRecordingToOutputFile(segmentUrl, movieSegmentWriter);
        }
Exemplo n.º 6
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;
            }
        }
Exemplo n.º 7
0
        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);
            }
        }
        public void StartRecording(object sender, EventArgs e)
        {
            //Make sure we're in a good state before we start recording
            if (!XamRecorder.IsPreviewing)
            {
                throw new Exception("You can't start recording until you are previewing.");
            }

            if (XamRecorder.IsRecording)
            {
                throw new Exception("You can't start recording because you are already recording.");
            }

            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var library   = System.IO.Path.Combine(documents, "..", "Library");

            XamRecorder.VideoFileName = System.IO.Path.Combine(library, "video.mov");

            NSUrl url = new NSUrl(XamRecorder.VideoFileName, false);

            NSFileManager manager = new NSFileManager();
            NSError       error   = new NSError();

            if (manager.FileExists(XamRecorder.VideoFileName))
            {
                manager.Remove(XamRecorder.VideoFileName, out error);
            }

            if (IsCameraAvailable)
            {
                AVCaptureFileOutputRecordingDelegate avDel = new iOSVideoRecorderDelegate();
                output.StartRecordingToOutputFile(url, avDel);
            }
            else
            {
                //No camera available - use the sample file
                FileInfo sample = new FileInfo("sample.mov");
                sample.CopyTo(XamRecorder.VideoFileName);
            }
            XamRecorder.IsRecording = true;
        }
Exemplo n.º 9
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);
            }
        }
Exemplo n.º 10
0
        public void StartVideoRecording(bool shouldSaveVideoToLibrary)
        {
            if (_videoFileOutput == null)
            {
                Console.WriteLine("capture session: trying to record a video but no movie file output is set");
                return;
            }

            _sessionQueue.DispatchAsync(() =>
            {
                // if already recording do nothing
                if (_videoFileOutput.Recording)
                {
                    Console.WriteLine(
                        "capture session: trying to record a video but there is one already being recorded");
                    return;
                }

                // start recording to a temporary file.
                var outputFileName = new NSUuid().AsString();

                var outputUrl = NSFileManager.DefaultManager.GetTemporaryDirectory().Append(outputFileName, false)
                                .AppendPathExtension("mov");

                var recordingDelegate = new VideoCaptureDelegate(DidStartCaptureAction,
                                                                 captureDelegate => DidFinishCaptureAction(captureDelegate, outputUrl),
                                                                 (captureDelegate, error) => DidCaptureFail(captureDelegate, error, outputUrl))
                {
                    ShouldSaveVideoToLibrary = shouldSaveVideoToLibrary
                };

                _videoFileOutput.StartRecordingToOutputFile(outputUrl, recordingDelegate);

                _videoCaptureDelegate = recordingDelegate;
            });
        }
        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();
            };
        }