private async Task RecordVideo()
 {
     if (!(Element as VideoCameraPage).IsRecording)
     {
         string filepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
         string filename = System.IO.Path.Combine(filepath, "video.mp4");
         if (File.Exists(filename))
         {
             File.Delete(filename);
         }
         recorder = new MediaRecorder();
         camera.Unlock();
         recorder.SetCamera(camera);
         recorder.SetVideoSource(VideoSource.Camera);
         recorder.SetAudioSource(AudioSource.Mic);
         recorder.SetProfile(CamcorderProfile.Get(0, CamcorderQuality.High));
         //recorder.SetVideoEncoder(VideoEncoder.Default);
         //recorder.SetAudioEncoder(AudioEncoder.Default);
         //recorder.SetOutputFormat(OutputFormat.Mpeg4);
         recorder.SetOutputFile(filename);
         recorder.Prepare();
         recorder.Start();
         (Element as VideoCameraPage).IsRecording = true;
     }
 }
Example #2
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            //If authorisation not granted for camera
            if (ContextCompat.CheckSelfPermission(CurrentContext, Manifest.Permission.Camera) != Permission.Granted)
            {
                //ask for authorisation
                ActivityCompat.RequestPermissions(CurrentContext, new System.String[] { Manifest.Permission.Camera }, 50);
            }
            else
            {
                if (camera != null)
                {
                    camera.Release();
                    camera = null;
                }
                camera = Android.Hardware.Camera.Open();
                camera.SetDisplayOrientation(90);


                Parameters parameters = camera.GetParameters();
                parameters.FocusMode = Parameters.FocusModeContinuousVideo;
                camera.SetParameters(parameters);

                camera.SetPreviewDisplay(holder);
                camera.StartPreview();
                initRecorder();
                camera.Unlock();
            }

            prepareRecorder();
        }
Example #3
0
 public void OnPictureTaken(byte[] data, Camera camera)
 {
     if (data != null)
     {
         Photo = data;
         _camera.Unlock();
         _camera.StopPreview();
         _camera.Release();
     }
 }
Example #4
0
 private void InitCamera()
 {
     try
     {
         camera = Android.Hardware.Camera.Open();
         camera.SetDisplayOrientation(90);
         camera.Unlock();
     }
     catch { }
 }
 private void prepare()
 {
     if (recorder == null)
     {
         recorder = new MediaRecorder();
     }
     recorder.Reset();
     if (camera != null)
     {
         camera.Unlock();
         recorder.SetCamera(camera);
     }
     recorder.SetVideoSource(VideoSource.Camera);
     recorder.SetAudioSource(AudioSource.Camcorder);
     recorder.SetOutputFormat(OutputFormat.Mpeg4);
     recorder.SetVideoEncoder(VideoEncoder.H264);
     recorder.SetAudioEncoder(AudioEncoder.Aac);
     recorder.SetOrientationHint(90);
     recorder.SetOutputFile(savePath);
     recorder.SetMaxDuration(10 * 1000);
     recorder.SetMaxFileSize(5 * 1000 * 1000);
     recorder.SetVideoEncodingBitRate(2 * 1024 * 1024);
     if (supportFrameRate > 0)
     {
         recorder.SetVideoFrameRate(supportFrameRate);
     }
     //recorder.SetPreviewDisplay(vv.Holder.Surface);
     if (videoSizeList != null && videoSizeList.Count > 0)
     {
         recorder.SetVideoSize(videoSizeList[bestIndex].Width, videoSizeList[bestIndex].Height);
     }
     try
     {
         recorder.Prepare();
     }
     catch (Exception e)
     {
         Console.Out.WriteLine("===prepare error:" + e);
     }
 }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            var metrics = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetRealMetrics(metrics);

            ScreenX = metrics.WidthPixels;
            ScreenY = metrics.HeightPixels;

            number = 0;
            SetContentView(Resource.Layout.CameraTakePicScreen);
            isRunning = false;
            var header = FindViewById<TextView>(Resource.Id.txtFirstScreenHeader);
            var btns = FindViewById<ImageView>(Resource.Id.imgNewUserHeader);
            var relLayout = FindViewById<RelativeLayout>(Resource.Id.relativeLayout1);
            ImageHelper.setupTopPanel(btns, header, relLayout, header.Context);

            Header.headertext = Application.Context.Resources.GetString(Resource.String.photoTitle);
            Header.fontsize = 32f;
            ImageHelper.fontSizeInfo(header.Context);
            header.SetTextSize(Android.Util.ComplexUnitType.Dip, Header.fontsize);
            header.Text = Header.headertext;

            var surface = FindViewById<SurfaceView>(Resource.Id.surfaceCameraView);

            holder = surface.Holder;
            holder.AddCallback(this);
            context = surface.Context;

            var takePicture = FindViewById<ImageButton>(Resource.Id.btnCamera);
            takePicture.Tag = 1;
            var flipView = FindViewById<ImageButton>(Resource.Id.imgFlipView);
            flipView.Tag = 2;
            var returnBack = FindViewById<ImageButton>(Resource.Id.imgBack);
            returnBack.Tag = 0;
            var bottom = FindViewById<LinearLayout>(Resource.Id.bottomHolder);

            var btn = new ImageButton[3];
            btn[0] = returnBack;
            btn[1] = takePicture;
            btn[2] = flipView;

            ImageHelper.setupButtonsPosition(btn, bottom, context);

            var cameraInfo = new Android.Hardware.Camera.CameraInfo();
            camera = null;

            int cameraCount = Android.Hardware.Camera.NumberOfCameras;
            if (cameraCount == 1)
                flipView.Visibility = ViewStates.Invisible;
            else
            {
                flipView.Click += delegate
                {
                    if (isRunning)
                    {
                        camera.StopPreview();
                        isRunning = false;
                        camera.Unlock();

                        if (cameraCount > 1 && camID < cameraCount - 1)
                            camID++;
                        else
                            camID--;

                        camera = Android.Hardware.Camera.Open(camID);
                        isRunning = true;

                        camera.Lock();
                        camera.StartPreview();
                    }
                };
            }
            takePicture.Click += delegate
            {
                var p = camera.GetParameters();
                p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
                camera.SetParameters(p);
                camera.TakePicture(this, this, this);
            };

            returnBack.Click += (object sender, EventArgs e) =>
            {
                var resultData = new Intent();
                resultData.PutExtra("filename", fullFilename);
                SetResult(!string.IsNullOrEmpty(fullFilename) ? Result.Ok : Result.Canceled, resultData);
                Finish();
            };
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            number = 0;
            SetContentView(Resource.Layout.CameraTakePicScreen);
            isRunning = false;
            TextView header = FindViewById<TextView>(Resource.Id.txtFirstScreenHeader);
            ImageView btns = FindViewById<ImageView>(Resource.Id.imgNewUserHeader);
            RelativeLayout relLayout = FindViewById<RelativeLayout>(Resource.Id.relativeLayout1);
            ImageHelper.setupTopPanel(btns, header, relLayout, header.Context);

            Header.headertext = Application.Context.Resources.GetString(Resource.String.photoTitle);
            Header.fontsize = 36f;
            ImageHelper.fontSizeInfo(header.Context);
            header.SetTextSize(Android.Util.ComplexUnitType.Dip, Header.fontsize);
            header.Text = Header.headertext;

            SurfaceView surface = FindViewById<SurfaceView>(Resource.Id.surfaceCameraView);

            holder = surface.Holder;
            holder.AddCallback(this);
            holder.SetType(Android.Views.SurfaceType.PushBuffers);
            context = surface.Context;

            ImageButton takePicture = FindViewById<ImageButton>(Resource.Id.btnCamera);
            takePicture.Tag = 1;
            ImageButton flipView = FindViewById<ImageButton>(Resource.Id.imgFlipView);
            flipView.Tag = 2;
            ImageButton returnBack = FindViewById<ImageButton>(Resource.Id.imgBack);
            returnBack.Tag = 0;
            LinearLayout bottom = FindViewById<LinearLayout>(Resource.Id.bottomHolder);

            ImageButton[] btn = new ImageButton[3];
            btn [0] = returnBack;
            btn [1] = takePicture;
            btn [2] = flipView;

            ImageHelper.setupButtonsPosition(btn, bottom, context);

            int back = (int)Android.Hardware.CameraFacing.Back;
            int front = (int)Android.Hardware.CameraFacing.Front;

            Android.Hardware.Camera.CameraInfo cameraInfo = new Android.Hardware.Camera.CameraInfo();
            camera = null;

            int cameraCount = Android.Hardware.Camera.NumberOfCameras;
            if (cameraCount == 1)
                flipView.Visibility = ViewStates.Invisible;
            else
            {
                flipView.Click += delegate
                {
                    if (isRunning)
                    {
                        camera.StopPreview();
                        isRunning = false;
                        camera.Unlock();
                        //camera.Release();

                        if (cameraCount > 1 && camID < cameraCount - 1)
                            camID++;
                        else
                            camID--;

                        camera = Android.Hardware.Camera.Open(camID);
                        isRunning = true;

                        camera.Lock();
                        camera.StartPreview();
                    }
                };
            }
            takePicture.Click += delegate
            {
                Android.Hardware.Camera.Parameters p = camera.GetParameters();
                p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
                camera.SetParameters(p);
                camera.TakePicture(this, this, this);
            };

            returnBack.Click += (object sender, EventArgs e) =>
            {
                Intent resultData = new Intent();
                resultData.PutExtra("filename", fullFilename);
                if (fullFilename != "")
                    SetResult(Result.Ok, resultData);
                else
                    SetResult(Result.Canceled, resultData);
                Finish();
            };
        }
Example #8
0
        protected override void OnElementChanged(ElementChangedEventArgs <PocketPro.CameraPreview> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                cameraPreview = new CameraPreview(Context);
                cameraPreview.OnPictureReturn = e.NewElement.OnPictureReturn;
                cameraPreview.OnVideoStarted  = e.NewElement.OnVideoStarted;
                cameraPreview.OnVideoFinished = e.NewElement.OnVideoFinished;

                SetNativeControl(cameraPreview);
            }

            if (e.OldElement != null)
            {
                // Unsubscribe
                cameraPreview.Click -= OnCameraPreviewClicked;
            }

            if (e.NewElement != null)
            {
                Camera camera = null;

                e.NewElement.TakePhotoEvent += (sender, args) =>
                {
                    if (cameraPreview.Preview != null)
                    {
                        cameraPreview.OnPictureReturn = ((PocketPro.CameraPreview)(sender)).OnPictureReturn;
                        cameraPreview.OnVideoStarted  = ((PocketPro.CameraPreview)(sender)).OnVideoStarted;
                        cameraPreview.OnVideoFinished = ((PocketPro.CameraPreview)(sender)).OnVideoFinished;
                        //cameraPreview.Preview.AutoFocus(new AutofocusCallBack(cameraPreview)
                        //{
                        //    isTakePhoto = true
                        //});


                        cameraPreview.camera.EnableShutterSound(false);
                        cameraPreview.camera.TakePicture(new ShutterCallback(), null, new JpegCallback(this.cameraPreview));

                        //}
                        //else camera.AutoFocus(new AutofocusCallBack(cameraPreview)); // TODO: Verify No Memory Leak On Failure
                    }
                    else
                    {
                    }
                };

                e.NewElement.StartRecordingEvent += (sender, args) => {
                    cameraPreview.Preview.StopPreview();
                    cameraPreview.Preview.Release();

                    var cameraOption = cameraOptions.Equals(CameraOptions.Front) ? CameraOptions.Front : CameraOptions.Rear;
                    var dcimPath     = Android.OS.Environment.GetExternalStoragePublicDirectory(Environment.DirectoryMovies).Path;

                    var sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                    var currentDateandTime = sdf.Format(new Date());
                    var filename           = $"PocketPro - {currentDateandTime}.mp4";
                    var dcimFilePath       = System.IO.Path.Combine(dcimPath, filename);

                    videoFilePath = dcimFilePath;

                    camera                = Camera.Open((int)cameraOption);
                    cameraOptions         = cameraOption;
                    cameraPreview.Preview = camera;
                    camera.Unlock();

                    try
                    {
                        mRecorder = new MediaRecorder();
                        mRecorder.SetCamera(camera);
                        mRecorder.SetVideoSource(VideoSource.Camera);
                        mRecorder.SetAudioSource(AudioSource.Mic);
                        mRecorder.SetOutputFormat(OutputFormat.Mpeg4);
                        mRecorder.SetVideoEncoder(VideoEncoder.H264);
                        mRecorder.SetAudioEncoder(AudioEncoder.Aac);
                        mRecorder.SetOutputFile(dcimFilePath);
                        mRecorder.SetOrientationHint(0);
                        mRecorder.SetVideoFrameRate(30);
                        // mRecorder.SetVideoEncodingBitRate(512 * 1000);
                        mRecorder.SetVideoSize(1920, 1080);
                        mRecorder.SetPreviewDisplay(cameraPreview.holder.Surface);
                        mRecorder.Prepare();
                        mRecorder.Start();
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.Message);
                    }
                };

                e.NewElement.StopRecordingEvent += (sender, args) => {
                    mRecorder.Stop();
                    mRecorder.Reset();
                    mRecorder.Release();

                    //camera = Camera.Open((int)cameraOption);
                    //cameraOptions = cameraOption;
                    //camera.Unlock();

                    var dcimPath     = Android.OS.Environment.GetExternalStoragePublicDirectory(Environment.DirectoryMovies).Path;
                    var fileBase     = System.IO.Path.GetFileNameWithoutExtension(videoFilePath);
                    var dcimFilePath = System.IO.Path.Combine(dcimPath, $"{fileBase}.png");

                    var brightnessService = DependencyService.Get <IRateApplication>();
                    var thumb             = brightnessService.GenerateThumbImage(videoFilePath, 1000);
                    System.IO.File.WriteAllBytes(dcimFilePath, thumb);
                };

                e.NewElement.ToggleCamera += (sender, args) =>
                {
                    cameraPreview.Preview.StopPreview();
                    cameraPreview.Preview.Release();

                    var cameraOption = cameraOptions.Equals(CameraOptions.Front) ? CameraOptions.Front : CameraOptions.Rear;

                    camera        = Camera.Open((int)cameraOption);
                    cameraOptions = cameraOption;

                    cameraPreview.Preview = camera;
                    cameraPreview.Preview.StartPreview();

                    cameraPreview = new CameraPreview(Context);
                    cameraPreview.OnPictureReturn = e.OldElement.OnPictureReturn;
                    cameraPreview.OnVideoStarted  = e.OldElement.OnVideoStarted;
                    cameraPreview.OnVideoFinished = e.OldElement.OnVideoFinished;

                    SetNativeControl(cameraPreview);

                    Control.Preview = camera;
                    Control.Preview.StartPreview();
                };

                e.NewElement.AutoFocusEvent += (sender, args) =>
                {
                    cameraPreview.Preview.AutoFocus(new AutofocusCallBack(cameraPreview));
                };

                e.NewElement.EnableTorchEvent += (sender, args) =>
                {
                    var parameters = cameraPreview.Preview.GetParameters();
                    parameters.FlashMode = Camera.Parameters.FlashModeTorch;
                    //cameraPreview.Preview.StopPreview();
                    cameraPreview.Preview.SetParameters(parameters);
                };

                e.NewElement.DisableTorchEvent += (sender, args) =>
                {
                    var parameters = cameraPreview.Preview.GetParameters();
                    parameters.FlashMode = Camera.Parameters.FlashModeOff;
                    //cameraPreview.Preview.StartPreview();
                    cameraPreview.Preview.SetParameters(parameters);
                };

                // Subscribe
                cameraPreview.Click += OnCameraPreviewClicked;
                try
                {
                    if (camera == null)
                    {
                        Control.Preview = Camera.Open((int)e.NewElement.Camera);
                    }
                }
                catch (Exception cameraException)
                {
                    Console.WriteLine(cameraException.Message);
                }
            }
        }