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
 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();
 }
        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.º 4
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();
        }
 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);
     }
 }
Exemplo n.º 7
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 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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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));
            }
        }