Exemplo n.º 1
0
        private void SetUpMediaRecorder(string saveFilePath)
        {
            if (_recorder == null)
            {
                //MediaRecorderの設定
                _recorder = new MediaRecorder();

                // 入力ソースの設定
                _recorder.SetVideoSource(VideoSource.Surface);      // 録画の入力ソースを指定
                //_recorder.SetAudioSource(AudioSource.Mic);          // 音声の入力ソースを指定

                // ファイルフォーマットの設定
                _recorder.SetOutputFormat(OutputFormat.ThreeGpp);    // ファイルフォーマットを指定

                // エンコーダーの設定
                //_recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);             // ビデオエンコーダを指定
                //_recorder.SetAudioEncoder(AudioEncoder.AmrNb);             // オーディオエンコーダを指定
                _recorder.SetVideoEncoder(VideoEncoder.H264);             // ビデオエンコーダを指定
                //_recorder.SetAudioEncoder(AudioEncoder.Aac);             // オーディオエンコーダを指定

                // 各種設定
                _recorder.SetOutputFile(saveFilePath);              // 動画の出力先となるファイルパスを指定
                _recorder.SetVideoEncodingBitRate(10000000);
                _recorder.SetVideoFrameRate(29);                    //信号機の点滅レートも30  動画のフレームレートを指定
                _recorder.SetVideoSize(320, 240);                   // 動画のサイズを指定

                _recorder.Prepare();                                // 録画準備
            }
        }
Exemplo n.º 2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.VideoRecord);

            var record = FindViewById <Button>(Resource.Id.Record);
            var stop   = FindViewById <Button>(Resource.Id.Stop);
            var play   = FindViewById <Button>(Resource.Id.Play);
            var video  = FindViewById <VideoView>(Resource.Id.SampleVideoView);

            //displaying from camera

            /*Intent intent = new Intent(MediaStore.ActionVideoCapture);
             * StartActivityForResult(intent, 0);*/
            //displaying from camera ENDED

            String timeStamp = GetTimestamp(DateTime.Now);

            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/" + timeStamp + "test.mp4";

            record.Click += delegate
            {
                video.StopPlayback();

                recorder = new MediaRecorder();
                recorder.SetVideoSource(VideoSource.Camera);
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.Default);
                recorder.SetVideoEncoder(VideoEncoder.Default);
                recorder.SetAudioEncoder(AudioEncoder.Default);
                recorder.SetOutputFile(path);
                recorder.SetPreviewDisplay(video.Holder.Surface);
                recorder.Prepare();

                recorder.Start();
            };

            stop.Click += delegate
            {
                if (recorder != null)
                {
                    recorder.Stop();
                    recorder.Release();
                }
            };

            play.Click += delegate
            {
                var uri = Android.Net.Uri.Parse(path);
                video.SetVideoURI(uri);
                video.Start();
            };
        }
Exemplo n.º 3
0
 private void SetupMediaRecorder()
 {
     mediaRecorder.SetVideoSource(VideoSource.Surface);
     mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
     mediaRecorder.SetOutputFile(new File(sessionPath + "/video.mp4").AbsolutePath);
     mediaRecorder.SetVideoEncodingBitRate(10000000);
     mediaRecorder.SetVideoFrameRate(30);
     mediaRecorder.SetVideoSize(640, 480);
     mediaRecorder.SetVideoEncoder(VideoEncoder.H264);
     mediaRecorder.Prepare();
 }
Exemplo n.º 4
0
 private void SetRecorderProperties()
 {
     recorder = new MediaRecorder();
     recorder.SetCamera(camera);
     recorder.SetVideoSource(VideoSource.Camera);
     recorder.SetAudioSource(AudioSource.Mic);
     recorder.SetOutputFormat(OutputFormat.Mpeg4);
     recorder.SetVideoEncoder(VideoEncoder.H264);
     recorder.SetAudioEncoder(AudioEncoder.AmrNb);
     recorder.SetOutputFile(path);
     recorder.SetOrientationHint(90);
 }
Exemplo n.º 5
0
        public void StartRecord()
        {
            var video = Activity.FindViewById <VideoView>(Resource.Id.videoView1);

            video.StopPlayback();

            var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var filename  = System.IO.Path.Combine(documents, write_sequence.ToString() + ".MP4");

            File.Delete(filename);

            var cameraParameters      = camera.GetParameters();
            var supportedSizes        = cameraParameters.SupportedVideoSizes;
            var supportedPreviewSizes = cameraParameters.SupportedPreviewSizes;

            //        cameraParameters.Zoom = 30;

            camera.Unlock();

            recorder?.Release();
            recorder = null;

            recorder = new MediaRecorder();
            recorder.SetCamera(camera);

            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetAudioSource(AudioSource.Camcorder);
            recorder.SetOutputFormat(OutputFormat.Mpeg4);

            recorder.SetVideoSize(supportedSizes[0].Width, supportedSizes[0].Height);

            recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);
            recorder.SetAudioEncoder(AudioEncoder.AmrNb);


            // Change the stream to your stream of choice.



            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_ALARM, true);
            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_DTMF, true);
            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_MUSIC, true);
            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_RING, true);
            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_SYSTEM, true);
            //((AudioManager)activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_VOICE_CALL, true);

            recorder.SetPreviewDisplay(video.Holder.Surface);

            recorder.SetOutputFile(filename);
            recorder.Prepare();
            recorder.Start();
        }
Exemplo n.º 6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.frmVideo);
            btnGravar = (Button)FindViewById(Resource.Id.btnGravar);
            btnVoltar = (Button)FindViewById(Resource.Id.btnVoltar);
            btnParar  = (Button)FindViewById(Resource.Id.btnParar);
            btnTocar  = (Button)FindViewById(Resource.Id.btnTocar);
            video     = (VideoView)FindViewById(Resource.Id.video);
            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/teste.mp4";

            btnGravar.Click += delegate
            {
                video.StopPlayback();
                recorder = new MediaRecorder();
                recorder.SetVideoSource(VideoSource.Camera);
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.Default);
                recorder.SetVideoEncoder(VideoEncoder.Default);
                recorder.SetAudioEncoder(AudioEncoder.Default);
                recorder.SetOutputFile(path);
                recorder.SetPreviewDisplay(video.Holder.Surface);
                recorder.Prepare();
                recorder.Start();
            };

            btnParar.Click += delegate
            {
                if (recorder != null)
                {
                    recorder.Stop();
                    recorder.Release();
                }
            };

            btnTocar.Click += delegate
            {
                var uri = Android.Net.Uri.Parse(path);
                video.SetVideoURI(uri);
                video.Start();
            };
            btnVoltar.Click += (sender, e) =>
            {
                Intent intent = new Intent(this, typeof(MainActivity));
                StartActivity(intent);
            };
        }
Exemplo n.º 7
0
        public void StartRecording(RecordType type)
        {
            _type = type;

            if (_type == RecordType.None)
            {
                return;
            }

            try
            {
                _recorder        = new MediaRecorder();
                _recorder.Error += (o, e) =>
                {
                    _isRecording = false;
                    OnServiceChanged.Invoke(this, EventArgs.Empty);
                };

                _recorder.Reset();


                if (_type == RecordType.Video)
                {
                    _recorder.SetAudioSource(AudioSource.Camcorder);
                    _recorder.SetVideoSource(VideoSource.Camera);
                    _recorder.SetOutputFormat(OutputFormat.Mpeg4);
                    _recorder.SetVideoSize(640, 480);
                    _recorder.SetCaptureRate(30);
                    _recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);
                    _recorder.SetAudioEncoder(AudioEncoder.Aac);
                }
                else if (_type == RecordType.Audio)
                {
                    _recorder.SetAudioSource(AudioSource.Mic);
                    _recorder.SetOutputFormat(OutputFormat.Default);
                    _recorder.SetAudioEncoder(AudioEncoder.Default);
                }

                _recorder.SetOutputFile(GetFilePath());
                _recorder.Prepare();
                _recorder.Start();
                _isRecording = true;
                OnServiceChanged.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                _isRecording = false;
                OnServiceChanged.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
            }
        }
        private void startRecordingVideo()
        {
            if (null == Activity)
            {
                return;
            }


            media_recorder = new MediaRecorder();
            File file = getVideoFile(Activity);

            try {
                //UI
                button_video.SetText(Resource.String.stop);
                is_recording_video = true;

                //Configure the MediaRecorder
                media_recorder.SetAudioSource(AudioSource.Mic);
                media_recorder.SetVideoSource(VideoSource.Surface);
                media_recorder.SetOutputFormat(OutputFormat.Mpeg4);
                media_recorder.SetOutputFile(System.IO.Path.GetFullPath(file.ToString()));
                media_recorder.SetVideoEncodingBitRate(10000000);
                media_recorder.SetVideoFrameRate(30);
                media_recorder.SetVideoSize(1440, 1080);
                media_recorder.SetVideoEncoder(VideoEncoder.H264);
                media_recorder.SetAudioEncoder(AudioEncoder.Aac);
                int rotation    = (int)Activity.WindowManager.DefaultDisplay.Rotation;
                int orientation = ORIENTATIONS.Get(rotation);
                media_recorder.SetOrientationHint(orientation);
                media_recorder.Prepare();
                Surface surface = media_recorder.Surface;

                //Set up CaptureRequest
                builder = camera_device.CreateCaptureRequest(CameraTemplate.Record);
                builder.AddTarget(surface);
                var preview_surface = new Surface(texture_view.SurfaceTexture);
                builder.AddTarget(preview_surface);
                var surface_list = new List <Surface>();
                surface_list.Add(surface);
                surface_list.Add(preview_surface);
                camera_device.CreateCaptureSession(surface_list, new RecordingCaptureStateListener(this), null);
            } catch (IOException e) {
                e.PrintStackTrace();
            } catch (CameraAccessException e) {
                e.PrintStackTrace();
            } catch (IllegalStateException e) {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 9
0
 private MediaRecorder ConfigurateRecoder()
 {
     mediaRecorder = new MediaRecorder();
     mediaRecorder.SetCamera(camera);
     mediaRecorder.SetAudioSource(AudioSource.Camcorder);
     mediaRecorder.SetVideoSource(VideoSource.Camera);
     mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
     mediaRecorder.SetAudioEncoder(AudioEncoder.Aac);
     mediaRecorder.SetVideoEncoder(VideoEncoder.H264);
     mediaRecorder.SetVideoSize(640, 480);
     mediaRecorder.SetVideoFrameRate(16);
     mediaRecorder.SetVideoEncodingBitRate(3000000);
     mediaRecorder.SetPreviewDisplay(prevImage.Holder.Surface);
     return(mediaRecorder);
 }
        void PrepareMediaRecorder()
        {
            if (mediaRecorder == null)
            {
                mediaRecorder = new MediaRecorder();
            }
            else
            {
                mediaRecorder.Reset();
            }

            var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);

            if (map == null)
            {
                return;
            }

            videoFileName = Guid.NewGuid().ToString();

            var storageDir      = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMovies);
            var storageFilePath = storageDir + Java.IO.File.Separator + "AndroidCamera2Demo" + Java.IO.File.Separator + "Videos" + Java.IO.File.Separator;

            videoFileName = storageFilePath + videoFileName;

            var file = new Java.IO.File(storageFilePath);

            if (!file.Exists())
            {
                file.Mkdirs();
            }

            mediaRecorder.SetAudioSource(AudioSource.Mic);
            mediaRecorder.SetVideoSource(VideoSource.Surface);
            mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
            mediaRecorder.SetOutputFile(videoFileName);
            mediaRecorder.SetVideoEncodingBitRate(10000000);
            mediaRecorder.SetVideoFrameRate(30);
            var videoSize = ChooseVideoSize(map.GetOutputSizes(Java.Lang.Class.FromType(typeof(MediaRecorder))));

            mediaRecorder.SetVideoEncoder(VideoEncoder.H264);
            mediaRecorder.SetAudioEncoder(AudioEncoder.Aac);
            mediaRecorder.SetVideoSize(videoSize.Width, videoSize.Height);
            int rotation = (int)WindowManager.DefaultDisplay.Rotation;

            mediaRecorder.SetOrientationHint(GetOrientation(rotation));
            mediaRecorder.Prepare();
        }
Exemplo n.º 11
0
        private async void TakeVideoButtonTapped(object sender, EventArgs e)
        {
            var video = FindViewById <VideoView>(Resource.Id.MyVideoView);

            video.StopPlayback();
            string path = "Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + /test.mp4";

            recorder = new MediaRecorder();
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetAudioSource(AudioSource.Mic);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetAudioEncoder(AudioEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(video.Holder.Surface);
            recorder.Prepare();
            recorder.Start();
        }
Exemplo n.º 12
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Video);

            var record = FindViewById <Button>(Resource.Id.Record);
            var stop   = FindViewById <Button>(Resource.Id.Stop);
            var play   = FindViewById <Button>(Resource.Id.Play);
            var video  = FindViewById <VideoView>(Resource.Id.SampleVideoView);

            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";

            record.Click += delegate {
                video.StopPlayback();

                recorder = new MediaRecorder();
                recorder.SetVideoSource(VideoSource.Camera);
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.Default);
                recorder.SetVideoEncoder(VideoEncoder.Default);
                recorder.SetAudioEncoder(AudioEncoder.Default);
                recorder.SetOutputFile(path);
                recorder.SetPreviewDisplay(video.Holder.Surface);
                recorder.Prepare();
                recorder.Start();
            };

            stop.Click += delegate {
                if (recorder != null)
                {
                    recorder.Stop();
                    recorder.Release();
                }
            };

            play.Click += delegate {
                var uri = Android.Net.Uri.Parse(path);
                video.SetVideoURI(uri);
                video.Start();
            };
        }
Exemplo n.º 13
0
        private async void TakePhotoButtonTapped(object sender, EventArgs e)
        {
            //camera.StopPreview ();
            //DialogService.ShowLoading ("Capturing Every Pixel");

            //var image = textureView.Bitmap;
            //using (var imageStream = new MemoryStream ()) {
            //	await image.CompressAsync (Bitmap.CompressFormat.Jpeg, 50, imageStream);
            //	image.Recycle ();
            //	imageBytes = imageStream.ToArray ();
            //}

            //var navigationPage = new NavigationPage (new DrawMomentPage (imageBytes)) {
            //	BarBackgroundColor = Colors.NavigationBarColor,
            //	BarTextColor = Colors.NavigationBarTextColor
            //};

            //DialogService.HideLoading ();
            //camera.StartPreview ();
            //await App.Current.MainPage.Navigation.PushModalAsync (navigationPage, false);

            //var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);

            vv.StopPlayback();
            string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";

            camera = global::Android.Hardware.Camera.Open();
            camera.SetDisplayOrientation(90);
            recorder = new MediaRecorder();
            camera.Unlock();
            recorder.SetCamera(camera);
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetAudioSource(AudioSource.Mic);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetAudioEncoder(AudioEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(vv.Holder.Surface);
            recorder.Prepare();
            recorder.Start();
        }
Exemplo n.º 14
0
        public void StartRecord(object video_obj)
        {
            VideoView video = video_obj as VideoView;

            InitCamera();

            video.StopPlayback();

            var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var filename  = System.IO.Path.Combine(documents, "Write.MP4");

            File.Delete(filename);

            var cameraParameters      = camera.GetParameters();
            var supportedSizes        = cameraParameters.SupportedVideoSizes;
            var supportedPreviewSizes = cameraParameters.SupportedPreviewSizes;

            camera.Unlock();

            recorder?.Release();
            recorder = null;

            recorder = new MediaRecorder();
            recorder.SetCamera(camera);

            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetAudioSource(AudioSource.Camcorder);
            recorder.SetOutputFormat(OutputFormat.Mpeg4);

            recorder.SetVideoSize(supportedSizes[0].Width, supportedSizes[0].Height);

            recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);
            recorder.SetAudioEncoder(AudioEncoder.AmrNb);

            recorder.SetPreviewDisplay(video.Holder.Surface);

            recorder.SetOutputFile(filename);
            recorder.Prepare();
            recorder.Start();
        }
Exemplo n.º 15
0
        private bool PrepareMediaRecorder()
        {
            outputPath = new Java.IO.File(Activity.GetExternalFilesDir(null),
                                          DateTime.UtcNow.ToString("MM-dd-yyyy-HH-mm-ss-fff") + ".mp4").AbsolutePath;

            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            Camera.Parameters parameters = camera.GetParameters();
            camera.Unlock();
            mediaRecorder = new MediaRecorder();
            mediaRecorder.SetOutputFile(outputPath);
            mediaRecorder.SetCamera(camera);
            mediaRecorder.SetAudioSource(AudioSource.Camcorder);
            mediaRecorder.SetVideoSource(VideoSource.Camera);
            mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
            mediaRecorder.SetVideoFrameRate(30);
            mediaRecorder.SetVideoEncodingBitRate(5000000);
            mediaRecorder.SetVideoEncoder(VideoEncoder.H264);
            mediaRecorder.SetAudioEncoder(AudioEncoder.Aac);
            mediaRecorder.SetAudioSamplingRate(44100);
            mediaRecorder.SetAudioEncodingBitRate(96000);
            mediaRecorder.SetVideoSize(parameters.PictureSize.Width, parameters.PictureSize.Height);
            mediaRecorder.SetMaxDuration(600000); // ten mins

            try
            {
                mediaRecorder.Prepare();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                ReleaseMediaRecorder();
                return(false);
            }

            return(true);
        }
 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);
     }
 }
        private void SetUpMediaRecorder()
        {
            mediaRecorder.SetVideoSource(VideoSource.Surface);
            mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);

            mediaRecorder.SetOutputFile(videoPath.AbsolutePath);
            mediaRecorder.SetVideoEncodingBitRate(bitRate);
            mediaRecorder.SetVideoFrameRate(frameRate);
            mediaRecorder.SetVideoSize(videoSize.Width, videoSize.Height);
            mediaRecorder.SetVideoEncoder(videoCodec);

            mediaRecorder.Prepare();

            try
            {
                mediaRecorder.Start();
            }
            catch (Java.Lang.IllegalStateException e)
            {
                Log.Error(TAG, "Exception starting capture: " + e.Message, e);
            }
        }
Exemplo n.º 18
0
        public void RecordVideoToPath(SurfaceView Sv, string VideoPath)
        {
            // setup and configure recorder
            _mediaRecorder = new MediaRecorder();

            // set the input source
            _mediaRecorder.SetAudioSource(Android.Media.AudioSource.Mic);
            _mediaRecorder.SetVideoSource(Android.Media.VideoSource.Camera);

            // set encoding values
            _mediaRecorder.SetAudioEncoder(Android.Media.AudioEncoder.Default);
            _mediaRecorder.SetVideoEncoder(Android.Media.VideoEncoder.Default);

            // set the desirable preview display
            _mediaRecorder.SetPreviewDisplay(Sv.Holder.Surface);

            // set output file locationa and format
            _mediaRecorder.SetOutputFormat(Android.Media.OutputFormat.Default);
            _mediaRecorder.SetOutputFile(VideoPath);

            _mediaRecorder.Prepare();
        }
Exemplo n.º 19
0
        private void StartRecordingObject()
        {
            try
            {
                ActivityCompat.RequestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
                    );

                string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
                mMediaRecorder.SetVideoSource(VideoSource.Surface);
                mMediaRecorder.SetOutputFormat(OutputFormat.Webm);
                //mMediaRecorder.SetVideoEncodingBitRate(512 * 1000);
                mMediaRecorder.SetVideoEncoder(VideoEncoder.Vp8);
                mMediaRecorder.SetVideoSize(1280, 720);
                //mMediaRecorder.SetVideoFrameRate(10);
                mMediaRecorder.SetOutputFile(path);
                mMediaRecorder.Prepare();
            }
            catch (Exception e)
            {
            }
        }
Exemplo n.º 20
0
        //start recording video
        public void StartRecording(string file, FlashMode flashMode, int width, int heigth, int rotation)
        {
            if (mMediaRecorder != null)
            {
                return;
            }

            MediaRecorder recorder = new MediaRecorder();

            recorder.SetVideoSource(VideoSource.Surface);
            recorder.SetAudioSource(AudioSource.Mic);
            recorder.SetOutputFormat(OutputFormat.Mpeg4);
            recorder.SetOutputFile(file);
            recorder.SetVideoEncodingBitRate(6000000);
            recorder.SetVideoFrameRate(30);
            recorder.SetVideoSize(width, heigth);
            recorder.SetVideoEncoder(VideoEncoder.H264);
            recorder.SetAudioEncoder(AudioEncoder.Aac);

            recorder.SetOrientationHint(rotation);
            recorder.Prepare();

            List <Surface> surfaces = new List <Surface>();

            surfaces.Add(recorder.Surface);

            if (_TextureView != null)
            {
                surfaces.Add(getPreviewSurface());
            }

            createCapture(surfaces, flashMode, true, mDevice.CreateCaptureRequest(CameraTemplate.Record));
            recorder.Start();
            mMediaRecorder = recorder;
            mMediaFile     = file;
        }
Exemplo n.º 21
0
        // Should not be called by the UI thread
        private MP4Config testMediaRecorderAPI()
        {
            System.String key = PREF_PREFIX + "h264-mr-" + mRequestedQuality.framerate + "," + mRequestedQuality.resX + "," + mRequestedQuality.resY;

            if (mSettings != null && mSettings.Contains(key))
            {
                System.String[] s = mSettings.GetString(key, "").Split(',');
                return(new MP4Config(s[0], s[1], s[2]));
            }

            if (!Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted))
            {
                throw new StorageUnavailableException("No external storage or external storage not ready !");
            }

            System.String TESTFILE = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/spydroid-test.mp4";

            Log.Info(TAG, "Testing H264 support... Test file saved at: " + TESTFILE);

            try {
                File file = new File(TESTFILE);
                file.CreateNewFile();
            } catch (IOException e) {
                throw new StorageUnavailableException(e.Message);
            }

            // Save flash state & set it to false so that led remains off while testing h264
            bool savedFlashState = mFlashEnabled;

            mFlashEnabled = false;

            bool previewStarted = mPreviewStarted;

            bool cameraOpen = mCamera != null;

            createCamera();

            // Stops the preview if needed
            if (mPreviewStarted)
            {
                lockCamera();
                try {
                    mCamera.stopPreview();
                } catch (Exception e) {}
                mPreviewStarted = false;
            }

            try {
                Thread.Sleep(100);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.PrintStackTrace();
            }

            unlockCamera();

            try {
                mMediaRecorder = new MediaRecorder();
                mMediaRecorder.SetCamera(mCamera);
                mMediaRecorder.SetVideoSource(VideoSource.Camera);
                mMediaRecorder.SetOutputFormat(OutputFormat.ThreeGpp);
                mMediaRecorder.SetVideoEncoder((VideoEncoder)mVideoEncoder);
                mMediaRecorder.SetPreviewDisplay(mSurfaceView.Holder.Surface);
                mMediaRecorder.SetVideoSize(mRequestedQuality.resX, mRequestedQuality.resY);
                mMediaRecorder.SetVideoFrameRate(mRequestedQuality.framerate);
                mMediaRecorder.SetVideoEncodingBitRate((int)(mRequestedQuality.bitrate * 0.8));
                mMediaRecorder.SetOutputFile(TESTFILE);
                mMediaRecorder.SetMaxDuration(3000);

                // We wait a little and stop recording
                mMediaRecorder.SetOnInfoListener(this);

                /*mMediaRecorder.SetOnInfoListener(new MediaRecorder.IOnInfoListener() {
                 *                  public void onInfo(MediaRecorder mr, int what, int extra) {
                 *                          Log.d(TAG,"MediaRecorder callback called !");
                 *                          if (what==MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                 *                                  Log.d(TAG,"MediaRecorder: MAX_DURATION_REACHED");
                 *                          } else if (what==MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
                 *                                  Log.d(TAG,"MediaRecorder: MAX_FILESIZE_REACHED");
                 *                          } else if (what==MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN) {
                 *                                  Log.d(TAG,"MediaRecorder: INFO_UNKNOWN");
                 *                          } else {
                 *                                  Log.d(TAG,"WTF ?");
                 *                          }
                 *                          mLock.release();
                 *                  }
                 *          });*/

                // Start recording
                mMediaRecorder.Prepare();
                mMediaRecorder.Start();

                if (mLock.TryAcquire(6, TimeUnit.Seconds))
                {
                    Log.d(TAG, "MediaRecorder callback was called :)");
                    Thread.Sleep(400);
                }
                else
                {
                    Log.d(TAG, "MediaRecorder callback was not called after 6 seconds... :(");
                }
            } catch (IOException e) {
                throw new ConfNotSupportedException(e.Message);
            } catch (RuntimeException e) {
                throw new ConfNotSupportedException(e.Message);
            } catch (InterruptedException e) {
                e.PrintStackTrace();
            } finally {
                try {
                    mMediaRecorder.stop();
                } catch (Java.Lang.Exception e) {}
                mMediaRecorder.Release();
                mMediaRecorder = null;
                lockCamera();
                if (!cameraOpen)
                {
                    destroyCamera();
                }
                // Restore flash state
                mFlashEnabled = savedFlashState;
                if (previewStarted)
                {
                    // If the preview was started before the test, we try to restart it.
                    try {
                        startPreview();
                    } catch (Java.Lang.Exception e) {}
                }
            }

            // Retrieve SPS & PPS & ProfileId with MP4Config
            MP4Config config = new MP4Config(TESTFILE);

            // Delete dummy video
            File file = new File(TESTFILE);

            if (!file.Delete())
            {
                Log.e(TAG, "Temp file could not be erased");
            }

            Log.i(TAG, "H264 Test succeded...");

            // Save test result
            if (mSettings != null)
            {
                ISharedPreferencesEditor editor = mSettings.Edit();
                editor.PutString(key, config.getProfileLevel() + "," + config.getB64SPS() + "," + config.getB64PPS());
                editor.Commit();
            }

            return(config);
        }
Exemplo n.º 22
0
        public void Start(bool microphoneEnabled)
        {
            if (IsRunning)
            {
                return;
            }

            IsRunning = !IsRunning;

            // 权限判断
            if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(mainActivity,
                                                  new String[] { Manifest.Permission.WriteExternalStorage }, REQUEST_PERMISSIONS);
            }

            if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.RecordAudio) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(mainActivity,
                                                  new String[] { Manifest.Permission.RecordAudio }, REQUEST_PERMISSIONS);
            }

            if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.CaptureSecureVideoOutput) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(mainActivity,
                                                  new String[] { Manifest.Permission.CaptureSecureVideoOutput }, REQUEST_PERMISSIONS);
            }


            var message = "";

            try
            {
                //初始化Recorder
                if (microphoneEnabled)
                {
                    mediaRecorder.SetAudioSource(AudioSource.Mic);
                }
                else
                {
                    mediaRecorder.SetAudioSource(AudioSource.Default);
                }
                mediaRecorder.SetVideoSource(VideoSource.Surface);

                mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
                //视频帧数
                mediaRecorder.SetVideoFrameRate(30);
                mediaRecorder.SetVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
                mediaRecorder.SetVideoEncodingBitRate(5 * 1024 * 1024);
                path = Path.Combine(SavePath, System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp4");
                mediaRecorder.SetOutputFile(path);

                mediaRecorder.SetAudioEncoder(AudioEncoder.AmrNb);
                mediaRecorder.SetVideoEncoder(VideoEncoder.H264);

                mediaRecorder.Prepare();

                Intent captureIntent = mediaProjectionManager.CreateScreenCaptureIntent();
                //Form.Context is same as your MainActivity. You should override your MainActivity.OnActivityResult instead.
                //or  https://martynnw.wordpress.com/2016/12/18/android-startactivityforresult-and-xamarin-forms/
                //or  https://forums.xamarin.com/discussion/81278/how-to-handle-the-result-of-startactivityforresult-in-forms
                mainActivity.StartActivityForResult(captureIntent, REQUEST_RECORD);

                message = "go to ActivityResult method";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                RecordStart?.Invoke(this, new ErrorEventArgs(message));
            }
        }
Exemplo n.º 23
0
	    /**
	     * Video encoding is done by a MediaRecorder.
	     */
	    protected override void encodeWithMediaRecorder()
        {

		    Log.Debug(TAG,"Video encoded using the MediaRecorder API");

		    // We need a local socket to forward data output by the camera to the packetizer
		    createSockets();

		    // Reopens the camera if needed
		    destroyCamera();
		    createCamera();

		    // The camera must be unlocked before the MediaRecorder can use it
		    unlockCamera();

		    try {
			    mMediaRecorder = new MediaRecorder();
			    mMediaRecorder.SetCamera(mCamera);
			    mMediaRecorder.SetVideoSource(VideoSource.Camera);
			    mMediaRecorder.SetOutputFormat(OutputFormat.ThreeGpp);
			    mMediaRecorder.SetVideoEncoder((VideoEncoder) mVideoEncoder);
			    mMediaRecorder.SetPreviewDisplay(mSurfaceView.Holder.Surface);
			    mMediaRecorder.SetVideoSize(mRequestedQuality.resX,mRequestedQuality.resY);
			    mMediaRecorder.SetVideoFrameRate(mRequestedQuality.framerate);

			    // The bandwidth actually consumed is often above what was requested 
			    mMediaRecorder.SetVideoEncodingBitRate((int)(mRequestedQuality.bitrate*0.8));

			    // We write the output of the camera in a local socket instead of a file !			
			    // This one little trick makes streaming feasible quiet simply: data from the camera
			    // can then be manipulated at the other end of the socket
			    FileDescriptor fd = null;
			    if (sPipeApi == PIPE_API_PFD) {
				    fd = mParcelWrite.FileDescriptor;
			    } else  {
				    fd = mSender.FileDescriptor;
			    }
			    mMediaRecorder.SetOutputFile(fd);

			    mMediaRecorder.Prepare();
			    mMediaRecorder.Start();

		    } catch (System.Exception e) {
			    throw new ConfNotSupportedException(e.Message);
		    }

		    InputStream inputStream = null;
            System.IO.Stream inputSStream = null;

		    if (sPipeApi == PIPE_API_PFD) {
                inputStream = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
		    } else  {
                inputSStream = mReceiver.InputStream;
		    }

		    // This will skip the MPEG4 header if this step fails we can't stream anything :(
		    try {
			    byte[] buffer = new byte[4];
			    // Skip all atoms preceding mdat atom
			    while (!Thread.Interrupted())
                {
                    if (inputSStream != null)
                    {
                        while (inputSStream.ReadByte() != 'm') ;
                        inputSStream.Read(buffer, 0, 3);
                    }
                    else
                    { 
				        while (inputStream.Read() != 'm');
                        inputStream.Read(buffer,0,3);
                    }

                    if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't') break;
			    }
		    } catch (IOException e) {
			    Log.Error(TAG,"Couldn't skip mp4 header :/");
			    stop();
			    throw e;
		    }

		    // The packetizer encapsulates the bit stream in an RTP stream and send it over the network
		    mPacketizer.setInputStream(inputStream);
            mPacketizer.setInputSStream(inputSStream);

            mPacketizer.start();

		    mStreaming = true;

	    }
Exemplo n.º 24
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);
                }
            }
        }
Exemplo n.º 25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.VideoPrise);

            // Get our button from the layout resource,
            // and attach an event to it
            var record = FindViewById <Button>(Resource.Id.Record);
            //var stop = FindViewById<Button>(Resource.Id.Stop);
            //var play = FindViewById<Button>(Resource.Id.Play);
            var video = FindViewById <VideoView>(Resource.Id.surface);

            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Retakem.mp4";


            /*stop.Click += delegate {
             *  if (recorder != null)
             *  {
             *      isStoped = true;
             *      recorder.Stop();
             *      recorder.Release();
             *  }
             * };*/

            camera = Camera.Open();
            camera.SetDisplayOrientation(90);
            camera.Unlock();


            record.Click += delegate {
                video.StopPlayback();
                recorder = new MediaRecorder();
                recorder.SetCamera(camera);
                recorder.SetVideoSource(VideoSource.Camera);
                recorder.SetAudioSource(AudioSource.Camcorder);
                recorder.SetOutputFormat(OutputFormat.Mpeg4);
                recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);
                recorder.SetAudioEncoder(AudioEncoder.HeAac);
                recorder.SetOutputFile(path);
                recorder.SetPreviewDisplay(video.Holder.Surface);
                recorder.SetOrientationHint(90);
                recorder.Prepare();
                recorder.Start();

                Thread.Sleep(15000);

                if (recorder != null)
                {
                    isStoped = true;
                    recorder.Stop();
                    recorder.Release();
                    recorder.Dispose();
                    recorder = null;
                    camera.StopPreview();
                    camera.Release();
                    camera.Dispose();
                }
                var uri = Android.Net.Uri.Parse(path);
                video.SetVideoURI(uri);
                //video.Start();
                Intent intent = new Intent(this, typeof(VideoReadActivity));
                StartActivity(intent);
            };

            /* play.Click += delegate {
             *   var uri = Android.Net.Uri.Parse(path);
             *   video.SetVideoURI(uri);
             *   video.Start();
             * };*/
        }
Exemplo n.º 26
0
        protected override async void OnCreate(Bundle bundle)
        {
            try
            {
                base.OnCreate(bundle);
                //Логин и пароль от ФТП
                client.Credentials = new NetworkCredential("u163406", "JzjTZ3OPl0Ob");
                Xamarin.Essentials.Platform.Init(this, bundle);
                SetContentView(Resource.Layout.activity_main);
                //Record - кнопка, остальные 2 - превью камер (по 1пикселю размером)
                var record     = FindViewById <Button>(Resource.Id.Record);
                var video      = FindViewById <VideoView>(Resource.Id.SampleVideoView);
                var frontvideo = FindViewById <VideoView>(Resource.Id.SampleVideoViewFront);

                //Ненужный блок, показывает уведомление если нету фронтальной камеры
                if (Camera.NumberOfCameras < 2)
                {
                    Toast.MakeText(this, "Front camera missing", ToastLength.Long).Show();
                    return;
                }
                //Задаём на переменную Camera фронталку (0 - задняя, 1 - фронт (наверно))
                var camera = Camera.Open(1);
                //Не уверен что параметры работают в принципе, но решил их оставить
                Android.Hardware.Camera.Parameters parameters = camera.GetParameters();
                parameters.SetPictureSize(1920, 1080);
                camera.SetParameters(parameters);
                camera.SetDisplayOrientation(90);
                var rearcamera = Camera.Open(0);
                Android.Hardware.Camera.Parameters rearparameters = rearcamera.GetParameters();
                rearparameters.SetPictureSize(1920, 1080);
                rearcamera.SetParameters(rearparameters);
                rearcamera.SetDisplayOrientation(90);

                //Первый обработчик, отвечает за заднюю камеру
                record.Click += async delegate
                {
                    i = 1;
                    while (i == 1)
                    {
                        try
                        {
                            rearcamera.Unlock();
                            recorder = new MediaRecorder();
                            recorder.SetCamera(rearcamera);
                            recorder.SetVideoSource(VideoSource.Camera);
                            recorder.SetAudioSource(AudioSource.Mic);
                            recorder.SetOutputFormat(OutputFormat.Default);
                            recorder.SetVideoEncoder(VideoEncoder.Default);
                            recorder.SetAudioEncoder(AudioEncoder.Default);
                            //Битрейт и разрешение.
                            recorder.SetVideoEncodingBitRate(12000);
                            recorder.SetVideoSize(1920, 1080);
                            //Адрес локального сохранения файла
                            recorder.SetOutputFile(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test" + a + ".mp4");
                            recorder.SetPreviewDisplay(video.Holder.Surface);
                            recorder.Prepare();
                            recorder.Start();
                            await Task.Delay(5000);

                            a++;
                            recorder.Stop();
                            recorder.Reset();
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                };
                //Обработчик кнопки, отвечающий за фронтальную камеру.
                record.Click += async delegate
                {
                    await sendfile();
                };
                record.Click += async delegate
                {
                    b = 1;
                    while (b == 1)
                    {
                        try
                        {
                            camera.Unlock();
                            frontrecorder = new MediaRecorder();
                            frontrecorder.SetCamera(camera);
                            frontrecorder.SetVideoSource(VideoSource.Camera);
                            frontrecorder.SetOutputFormat(OutputFormat.Default);
                            frontrecorder.SetVideoEncoder(VideoEncoder.Default);
                            //Битрейт и разрешение.
                            frontrecorder.SetVideoEncodingBitRate(6000);
                            frontrecorder.SetVideoSize(1280, 720);
                            //Адрес локального сохранения файла
                            frontrecorder.SetOutputFile(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/fronttest" + c + ".mp4");
                            frontrecorder.SetPreviewDisplay(frontvideo.Holder.Surface);
                            frontrecorder.Prepare();
                            frontrecorder.Start();
                            await Task.Delay(5000);

                            c++;
                            frontrecorder.Stop();
                            frontrecorder.Reset();
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                };
            }
            catch (System.Exception ex)
            {
            }
        }
Exemplo n.º 27
0
        private void initRecorder()
        {
            recorder = new MediaRecorder();
            path     = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/PincidentReport.mp4";

            recorder.SetCamera(camera);
            string manufacturer = Build.Manufacturer;

            if (ActivityCompat.CheckSelfPermission(CurrentContext, Manifest.Permission.RecordAudio) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(CurrentContext, new System.String[] { Manifest.Permission.RecordAudio },
                                                  10);
            }
            else
            {
                if (manufacturer.ToLower().Contains("samsung"))
                {
                    recorder.SetAudioSource(AudioSource.VoiceCommunication);
                }
                else
                {
                    recorder.SetAudioSource(AudioSource.Default);
                }
            }

            recorder.SetVideoSource(VideoSource.Camera);

            recorder.SetOutputFile(path);

            recorder.SetOnInfoListener(this);
            recorder.SetPreviewDisplay(videoView.Holder.Surface);
            recorder.SetOutputFormat(OutputFormat.Default);
            var SupportedVideoFrameRateByCamera = camera.GetParameters().SupportedPreviewFrameRates;
            var SmallToBigFrameRates            = SupportedVideoFrameRateByCamera.Reverse();

            var maxFrameRate = SmallToBigFrameRates.First().IntValue();

            recorder.SetVideoFrameRate(maxFrameRate);



            var SupportedSizesByCamera = camera.GetParameters().SupportedVideoSizes;

            var SmallToBigSizesList = SupportedSizesByCamera.Reverse();

            Android.Hardware.Camera.Size size = new Android.Hardware.Camera.Size(camera, 0, 0);


            foreach (var videoSize in SmallToBigSizesList) // The closest Height to 480
            {
                if (videoSize.Height == 480)
                {
                    size = videoSize;
                    break;
                }
                else if (videoSize.Height > 480)
                {
                    size = videoSize;
                    break;
                }
            }

            if (size.Height == 0)
            {
                size = SmallToBigSizesList.ElementAt(0);
            }

            recorder.SetVideoSize(size.Width, size.Height);

            recorder.SetVideoEncoder(VideoEncoder.Mpeg4Sp);// MPEG_4_SP
            recorder.SetAudioEncoder(AudioEncoder.Aac);

            recorder.SetMaxDuration(15000);

            recorder.SetOrientationHint(90);
        }