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 StartRecording() { var mManager = MainActivity.CurrentActivity.GetSystemService(Context.MediaProjectionService) as MediaProjectionManager; mediaProjection = mManager.GetMediaProjection((int)MainActivity.ReturnResultFromPermission, MainActivity.ReturnDataFromPermission); DisplayManager dManager = GetSystemService(Context.DisplayService) as DisplayManager; var displayMetrics = new DisplayMetrics(); dManager.GetDisplay(0).GetMetrics(displayMetrics); mediaRecorder = new MediaRecorder(); mediaRecorder.SetAudioSource(AudioSource.Mic); mediaRecorder.SetVideoSource(VideoSource.Surface); var profile = CamcorderProfile.Get(CamcorderQuality.High); profile.FileFormat = OutputFormat.Mpeg4; profile.VideoFrameHeight = displayMetrics.HeightPixels; profile.VideoFrameWidth = displayMetrics.WidthPixels; mediaRecorder.SetProfile(profile); mediaRecorder.SetOutputFile($"{Android.OS.Environment.ExternalStorageDirectory}/demovideo.mp4"); mediaRecorder.Prepare(); recordingDisplay = mediaProjection.CreateVirtualDisplay("Rec display", displayMetrics.WidthPixels, displayMetrics.HeightPixels, (int)displayMetrics.Density, Android.Views.DisplayFlags.Round, mediaRecorder.Surface, null, null); mediaRecorder.Start(); }
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()); } }
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; }
/// <summary> /// Surfaces the changed. /// </summary> /// <param name="holder">The holder.</param> /// <param name="format">The format.</param> /// <param name="w">The w.</param> /// <param name="h">The h.</param> public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h) { CameraWithId.Item2.StartPreview(); var postRotation = CameraHelper.GetCameraDisplayOrientation(CameraWithId.Item1); CameraWithId.Item2.SetDisplayOrientation(postRotation); var parameters = CameraWithId.Item2.GetParameters(); var profile = CamcorderProfile.Get(CameraWithId.Item1, CamcorderQuality.Q480p); parameters.SetPreviewSize(profile.VideoFrameWidth, profile.VideoFrameHeight); RequestLayout(); CameraWithId.Item2.SetParameters(parameters); }
//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); } }
// 繪製提示方框的 SurfaceHolderCallBack 3個function實作結束 //-------------------------------------------------------------- // 錄製影像函式定義 /* * void Rec_Click(object sender, EventArgs e) * { * Button btn = sender as Button; * timerViewer = FindViewById<TextView>(Resource.Id.counter); * if (!isRecing) * { * btn.Text = "測謊中"; * btn.Clickable = false; * Camera.StopPreview(); * Camera.Unlock(); * _MediaRecorder.SetCamera(Camera); * _MediaRecorder.SetMaxDuration(6000); * _MediaRecorder.SetVideoSource(VideoSource.Default); * _MediaRecorder.SetAudioSource(AudioSource.Mic); * _MediaRecorder.SetProfile( * CamcorderProfile.Get(CamcorderQuality.High)); * * _MediaRecorder.SetOutputFile(rec_video_uri); * * _MediaRecorder.SetPreviewDisplay(_Holder.Surface); * _MediaRecorder.SetOrientationHint * (_SurfaceHolderCallBack.RotataDegrees); * _MediaRecorder.Prepare(); * _MediaRecorder.Start(); * RunUpdateLoop(btn, e); * * } * else * { * btn.Clickable = true; * btn.Text = "開始測謊"; * _MediaRecorder.Stop(); * Camera.Reconnect(); * Camera.StartPreview(); * timerViewer.Text = "Recording Time: 0.0 s"; * } * isRecing = !isRecing; * } */ // For Testing three video recording: void Rec_Click(object sender, EventArgs e) { Button btn = sender as Button; timerViewer = FindViewById <TextView>(Resource.Id.counter); AlertDialog.Builder alert_rec = new AlertDialog.Builder(this); alert_rec.SetTitle("Recording Video_1"); alert_rec.SetMessage("第一題請要求受測者誠實回答問題,按下OK開始錄製影像."); alert_rec.SetIcon(Android.Resource.Drawable.IcDialogInfo); alert_rec.SetNegativeButton(" ok", new EventHandler <DialogClickEventArgs>((sender2, e2) => { if (!isRecing) { btn.Text = "測謊中"; btn.Clickable = false; Camera.StopPreview(); Camera.Unlock(); _MediaRecorder.SetCamera(Camera); _MediaRecorder.SetMaxDuration(6000); _MediaRecorder.SetVideoSource(VideoSource.Default); _MediaRecorder.SetAudioSource(AudioSource.Mic); _MediaRecorder.SetProfile( CamcorderProfile.Get(CamcorderQuality.High)); _MediaRecorder.SetOutputFile(rec_video_uri_1); _MediaRecorder.SetPreviewDisplay(_Holder.Surface); _MediaRecorder.SetOrientationHint (_SurfaceHolderCallBack.RotataDegrees); _MediaRecorder.Prepare(); _MediaRecorder.Start(); RunUpdateLoop_first(btn, e); } else { btn.Clickable = true; btn.Text = "開始測謊"; _MediaRecorder.Stop(); Camera.Reconnect(); Camera.StartPreview(); timerViewer.Text = "Recording Time: 0.0 s"; } isRecing = !isRecing; })); alert_rec.Show(); }
public void SetVideoQuality(CamcorderQuality quality, Android.Content.Res.Orientation orientation) { CamcorderProfile profile = CamcorderProfile.Get(quality); if (profile == null) { profile = CamcorderProfile.Get(CamcorderQuality.High); } if (orientation == Android.Content.Res.Orientation.Landscape) { SetVideoSize(profile.VideoFrameWidth, profile.VideoFrameHeight); } else { SetVideoSize(profile.VideoFrameHeight, profile.VideoFrameWidth); } SetVideoCodec(profile.VideoCodec); SetBitRate(profile.VideoBitRate); SetFrameRate(profile.VideoFrameRate); }
private void SetUpMediaRecorder() { if (null == _context) { return; } mediaRecorder = new MediaRecorder(); //changed this camcorder mediaRecorder.SetAudioSource(AudioSource.Camcorder); mediaRecorder.SetVideoSource(VideoSource.Surface); // mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4); //profile should be set after audio and video source and before //setting the output file //set this for test A mediaRecorder.SetProfile(CamcorderProfile.Get(CamcorderQuality.High)); string localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); videoFilePath = System.IO.Path.Combine(localFolder, $"video_{DateTime.Now.ToString("yyMMdd_hhmmss")}.mp4"); // var localPath = Android.OS.Environment.ExternalStorageDirectory + "/video1.mp4"; mediaRecorder.SetOutputFile(videoFilePath); //mediaRecorder.SetVideoEncodingBitRate(10000000); //mediaRecorder.SetVideoFrameRate(30); // Call this after setOutFormat() but before prepare(). mediaRecorder.SetVideoSize(videoSize.Width, videoSize.Height); //mediaRecorder.SetVideoEncoder(VideoEncoder.H264); //mediaRecorder.SetAudioEncoder(AudioEncoder.Aac); var windowManager = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>(); int rotation = (int)windowManager.DefaultDisplay.Rotation; int orientation = ORIENTATIONS.Get(rotation); mediaRecorder.SetOrientationHint(orientation); mediaRecorder.Prepare(); }
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); }
// Second private async void RunUpdateLoop_second(object sender, EventArgs e) { Button btn = sender as Button; Double count = 0.0; while (count <= 6.1) { if (count <= 6) { await Task.Delay(100); count = count + 0.1; timerViewer.Text = string.Format("Recording Time: {0,2:0.0} s", count); } else { btn.Clickable = true; btn.Text = "開始測謊"; _MediaRecorder.Stop(); Camera.Reconnect(); Camera.StartPreview(); timerViewer.Text = "Recording Time: 0.0 s"; isRecing = !isRecing; AlertDialog.Builder alert_rec = new AlertDialog.Builder(this); alert_rec.SetTitle("Recording Video_3"); alert_rec.SetMessage("第3題請詢問想測謊的問題,按下OK開始錄製影像."); alert_rec.SetIcon(Android.Resource.Drawable.IcDialogInfo); alert_rec.SetNegativeButton(" ok", new EventHandler <DialogClickEventArgs>((sender2, e2) => { if (!isRecing) { btn.Text = "測謊中"; btn.Clickable = false; Camera.StopPreview(); Camera.Unlock(); _MediaRecorder.SetCamera(Camera); _MediaRecorder.SetMaxDuration(6000); _MediaRecorder.SetVideoSource(VideoSource.Default); _MediaRecorder.SetAudioSource(AudioSource.Mic); _MediaRecorder.SetProfile( CamcorderProfile.Get(CamcorderQuality.High)); _MediaRecorder.SetOutputFile(rec_video_uri_3); _MediaRecorder.SetPreviewDisplay(_Holder.Surface); _MediaRecorder.SetOrientationHint (_SurfaceHolderCallBack.RotataDegrees); _MediaRecorder.Prepare(); _MediaRecorder.Start(); RunUpdateLoop_End(btn, e); } else { btn.Clickable = true; btn.Text = "開始測謊"; _MediaRecorder.Stop(); Camera.Reconnect(); Camera.StartPreview(); timerViewer.Text = "Recording Time: 0.0 s"; } isRecing = !isRecing; })); alert_rec.Show(); return; } } }
//.............................Main Principal...................................... protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource InitializeComponents(); SetContentView(Resource.Layout.Main); string date; string path = ""; var record = FindViewById <Button>(Resource.Id.recordBtn); var stop = FindViewById <Button>(Resource.Id.stopBtn); var play = FindViewById <Button>(Resource.Id.playBtn); var video = FindViewById <VideoView>(Resource.Id.videoView); bool isPlaying = false; CamcorderProfile cpHigh = CamcorderProfile.Get(CamcorderQuality.High); record.Click += delegate { video.StopPlayback(); isPlaying = true; recorder = new MediaRecorder(); recorder.SetVideoSource(VideoSource.Camera); recorder.SetAudioSource(AudioSource.Mic); //recorder.SetProfile(new CamcorderProfile()); //recorder.SetOutputFormat(OutputFormat.Mpeg4); //recorder.SetVideoEncoder(VideoEncoder.H264); //ecorder.SetAudioEncoder(AudioEncoder.Default); date = DateTime.Now.ToString("yyMMddHHmmss"); path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath + "video_" + date + ".mp4"; recorder.SetProfile(cpHigh); recorder.SetPreviewDisplay(video.Holder.Surface); recorder.SetOutputFile(path); recorder.Prepare(); StartCapturing(); captureGPS = false; recorder.Start(); record.Enabled = false; }; stop.Click += delegate { if (video.IsPlaying) { video.StopPlayback(); video.ClearAnimation(); } if (recorder != null && isPlaying) { recorder.Stop(); recorder.Release(); FinishCapturing(); ShowData(); } isPlaying = false; InitializeComponents(); record.Enabled = true; }; play.Click += delegate { Android.Net.Uri uri = Android.Net.Uri.Parse(path); video.SetVideoURI(uri); video.Start(); }; }
private bool prepareVideoRecorder() { // BEGIN_INCLUDE (configure_preview) mCamera = CameraHelper.getDefaultCameraInstance(); // We need to make sure that our preview and recording video size are supported by the // camera. Query camera to find all the sizes and choose the optimal size given the // dimensions of our preview surface. Camera.Parameters parameters = mCamera.GetParameters(); IList <Camera.Size> mSupportedPreviewSizes = parameters.SupportedPreviewSizes; IList <Camera.Size> mSupportedVideoSizes = parameters.SupportedVideoSizes; Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes, mSupportedPreviewSizes, mPreview.Width, mPreview.Height); // Use the same size for recording profile. CamcorderProfile profile = CamcorderProfile.Get(CamcorderQuality.High); profile.VideoFrameWidth = optimalSize.Width; profile.VideoFrameHeight = optimalSize.Height; // likewise for the camera object itself. parameters.SetPreviewSize(profile.VideoFrameWidth, profile.VideoFrameHeight); mCamera.SetParameters(parameters); try { // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay} // with {@link SurfaceView} mCamera.SetPreviewTexture(mPreview.SurfaceTexture); } catch (IOException e) { Log.Error(TAG, "Surface texture is unavailable or unsuitable" + e.Message); return(false); } // END_INCLUDE (configure_preview) // BEGIN_INCLUDE (configure_media_recorder) mMediaRecorder = new Android.Media.MediaRecorder(); // Step 1: Unlock and set camera to MediaRecorder mCamera.Unlock(); mMediaRecorder.SetCamera(mCamera); // Step 2: Set sources mMediaRecorder.SetAudioSource(AudioSource.Default); mMediaRecorder.SetVideoSource(VideoSource.Camera); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mMediaRecorder.SetProfile(profile); // Step 4: Set output file mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO); if (mOutputFile == null) { return(false); } mMediaRecorder.SetOutputFile(mOutputFile.Path); // END_INCLUDE (configure_media_recorder) // Step 5: Prepare configured MediaRecorder try { mMediaRecorder.Prepare(); } catch (IllegalStateException e) { Log.Debug(TAG, "IllegalStateException preparing MediaRecorder: " + e.Message); releaseMediaRecorder(); return(false); } catch (IOException e) { Log.Debug(TAG, "IOException preparing MediaRecorder: " + e.Message); releaseMediaRecorder(); return(false); } return(true); }