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;
     }
 }
        public void StartRecord(string filename)
        {
            if (recorder != null)
            {
                recorder.Reset();
            }
            else
            {
                recorder = new MediaRecorder();
            }
            mCamera.Lock();
            mCamera.Unlock();

            recorder.SetCamera(mCamera);
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetAudioSource(AudioSource.Camcorder);

            try
            {
                //try for full hd
                recorder.SetProfile(CamcorderProfile.Get(CURRENTCAMERA, CamcorderQuality.Q1080p));
            }
            catch
            {
                try
                {
                    recorder.SetProfile(CamcorderProfile.Get(CURRENTCAMERA, CamcorderQuality.Q720p));
                }
                catch
                {
                    try
                    {
                        //if not hd, try for highest phone can give
                        recorder.SetProfile(CamcorderProfile.Get(CURRENTCAMERA, CamcorderQuality.High));
                    }
                    catch
                    {
                        //if not, then set to low
                        recorder.SetProfile(CamcorderProfile.Get(CURRENTCAMERA, CamcorderQuality.Q480p));
                    }
                }
            }

            //recorder.SetAudioEncoder(AudioEncoder.Aac);
            //recorder.SetVideoEncoder(VideoEncoder.H264);
            recorder.SetPreviewDisplay(mPreview.Holder.Surface);
            recorder.SetOutputFile(filename);
            recorder.SetMaxDuration(1000 * 60 * 5);

            try
            {
                recorder.Prepare();
                recorder.Start();
            }
            catch (Exception e)
            {
                OnError?.Invoke(e.ToString());
            }
        }
Exemplo n.º 3
0
        public void StartRecording(object sender, EventArgs e)
        {
            ////Make sure we're in a good state before we start recording
            //if (!XamRecorder.IsPreviewing)
            //{
            //	throw new Exception("You can't start recording until you are previewing.");
            //}

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

            //Set path for the video file
            string filepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string filename = Path.Combine(filepath, "video.mp4");

            //string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/video.mp4";
            XamRecorder.VideoFileName = filename;

            if (IsCameraAvailable)
            {
                //Delete the file if it already exists
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }


                //Start recording
                recorder = new MediaRecorder();
                camera.Unlock();
                recorder.SetCamera(camera);
                recorder.SetVideoSource(VideoSource.Camera);
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetProfile(CamcorderProfile.Get(cameraId, CamcorderQuality.High));
                //recorder.SetVideoEncoder(VideoEncoder.Default); //Also tried default
                //recorder.SetAudioEncoder(AudioEncoder.Default); //Also tried default
                //recorder.SetOutputFormat(OutputFormat.Mpeg4);
                recorder.SetOutputFile(filename);

                recorder.SetPreviewDisplay(holder.Surface);

                recorder.Prepare();
                recorder.Start();
            }
            else
            {
                //Copy sample video to destiantion path just to have something there.
                FileInfo sample = new FileInfo("sample.mp4");
                sample.CopyTo(filename);
            }

            XamRecorder.IsPreviewing = true;
            XamRecorder.IsRecording  = true;
        }
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
 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);
 }
Exemplo n.º 7
0
        //PREPARAMOS NUESTRO MEDIA RECORD Y CAMARA
        private bool PrepararVideoRecorder()
        {
            //OBTENEMOS LA INSTANCIA DE NUESTRA CAMARA YA PREPARADA
            _camera = ObtenerInstanciaCamara();
            //INICIALIZAMOS NUESTRA VARIABLE MEDIARECORDER
            _mediaRecorder = new MediaRecorder();

            //LE INDICAMOS A NUESTRA CAMARA QUE CAMBIE DE ROTACION ESTO ES DEVIDO QUE POR DEFUALT NOS MUESTRA EN POSICION HORIZONTAL,
            //Y COMO DEFINIMOS QUE LA POSICION DE NUESTRA APP SEA Portrait, REALIZAMOS EL CAMBIO.
            _camera.SetDisplayOrientation(90);
            //ABRIMOS NUESTRA CAMARA PARA SER USADA
            _camera.Unlock();


            //DE IGUAL FORMA QUE NUESTRA CAMARA CAMBIAMOS LA POSICION DE NUESTRA MEDIARECORDER
            _mediaRecorder.SetOrientationHint(90);
            //ASIGNAMOS LA CAMARA A NUESTRA MEDIARECORDER
            _mediaRecorder.SetCamera(_camera);

            //ASIGNAMOS LOS FORMATOS DE VIDEO Y AUDIO
            _mediaRecorder.SetAudioSource(AudioSource.Camcorder);
            _mediaRecorder.SetVideoSource(VideoSource.Camera);

            //RECUPERAMOS EL PERFIL QUE TIENE NUESTRA CAMARA PARA PODER ASIGNARSELA A NUESTRA MEDIARECORDER
            var camcorderProfile = ((int)Build.VERSION.SdkInt) >= 9 ? CamcorderProfile.Get(0, CamcorderQuality.High) : CamcorderProfile.Get(CamcorderQuality.High);

            //ASIGNAMOS EL PERFIL A NUESTRO MEDIARECORDER
            _mediaRecorder.SetProfile(camcorderProfile);

            //LE ASIGNAMOS EL PATH DONDE SE ENCUESTRA NUESTRO ARCHIVO DE VIDEO PARA PODER CREARLO
            _mediaRecorder.SetOutputFile(PathArchivoVideo());


            //ASIGNAMOS EL SURFACE A NUESTRO MEDIARECORDER QUE UTILIZARA PARA VISUALIZAR LO QUE ESTAMOS GRABANDO
            _mediaRecorder.SetPreviewDisplay(_videoView.Holder.Surface);
            try
            {
                //CONFIRMAMOS LOS CAMBIOS HECHOS EN NUESTRO MEDIA RECORDER PARA PODER INICIAR A GRABAR
                _mediaRecorder.Prepare();
                return(true);
            }
            catch
            {
                //SI OCURRE ALGUN PROBLEMA LIBRAMOS LOS RECURSOS ASIGNADOS A NUESTRO MEDIARECORDER
                LiberarMediaRecorder();
                return(false);
            }
        }
Exemplo n.º 8
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.º 9
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();
        }
 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.º 11
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);
        }
Exemplo n.º 12
0
        private bool PrepareMediaRecorder()
        {
            camera   = Camera.Open();
            recorder = new MediaRecorder();

            camera.Unlock();
            recorder.SetCamera(camera);

            recorder.SetAudioSource(AudioSource.Camcorder);
            recorder.SetVideoSource(VideoSource.Camera);

            recorder.SetProfile(CamcorderProfile.Get(CamcorderQuality.High));

            recorder.SetOutputFile(GetOutputMediaFile(MediaType.Video).ToString());

            recorder.SetPreviewDisplay(preview.Holder.Surface);

            try
            {
                recorder.Prepare();
            }
            catch (IllegalStateException e)
            {
                Log.Debug("PrepareMediaRecorder", "Illegal state: " + e.Message);
                ReleaseMediaRecorder();
                return(false);
            }
            catch (IOException e)
            {
                Log.Debug("PrepareMediaRecorder", "IOException " + e.Message);
                ReleaseMediaRecorder();
                return(false);
            }

            return(true);
        }
Exemplo n.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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);
        }