Exemplo n.º 1
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Video);

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

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

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

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

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

            play.Click += delegate {
                var uri = Android.Net.Uri.Parse(path);
                video.SetVideoURI(uri);
                video.Start();
            };
        }
Exemplo n.º 2
0
        //[return: GeneratedEnum]
        //public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        //{
        //    return StartCommandResult.StickyCompatibility; // base.OnStartCommand(intent, flags, startId);
        //}
        protected override void OnHandleIntent(Intent intent)
        {
            //var cont = new WebClient().DownloadString("http://kurzweb.de/Tools/uploadfileex.txt");
            Functions.Notify(Application.Context, "dsfd", "Service");
            //System.Diagnostics.Debug.Print(" _____________________ ");
            //System.Diagnostics.Debug.Print("|                     |");
            //System.Diagnostics.Debug.Print("| DemoService started!|");
            //System.Diagnostics.Debug.Print("|_____________________|");
            #region "Media recorder"
            var mediaRecorder = new MediaRecorder();
            mediaRecorder.SetAudioSource(
                AudioSource.Mic);
            mediaRecorder.SetOutputFormat(
                OutputFormat.ThreeGpp);
            mediaRecorder.SetAudioEncoder(
                AudioEncoder.AmrNb);
            mediaRecorder.SetOutputFile("/dev/null");
            mediaRecorder.Prepare();
            mediaRecorder.Start();

            #endregion
            if (Global.ServiceTimer != null)
            {
                Global.ServiceTimer.Enabled = false;
                Global.ServiceTimer.Stop();
                Global.ServiceTimer.Dispose();
            }
            Global.ServiceTimer          = new Timer();
            Global.ServiceTimer.Interval = 1000;
            Global.ServiceTimer.Enabled  = true;
            Global.ServiceTimer.Elapsed += delegate
            {
                double db        = 10 * System.Math.Log(mediaRecorder.MaxAmplitude / 10);//20 * System.Math.Log10(mediaRecorder.MaxAmplitude) - 10 ;//0.00002 2700.0 32767 //-20 * System.Math.Log10(mediaRecorder.MaxAmplitude / 51805.5336 / 0.05)
                var    lastLevel = System.Math.Round(db, 0);
                //System.Diagnostics.Debug.Print(" _____________________ ");
                //System.Diagnostics.Debug.Print("|                     |");
                //System.Diagnostics.Debug.Print("|       " + lastLevel.ToString() + "       |");
                //System.Diagnostics.Debug.Print("|_____________________|");
                Functions.Notify(Application.Context, "dsfdf", "Timer");
            };
            Global.ServiceTimer.Start();
        }
Exemplo n.º 3
0
        private void RecordAudio()
        {
            if (isGrantedPermission)
            {
                SetUpMediaRecorder();
                try
                {
                    mediaRecorder.Prepare();
                    mediaRecorder.Start();

                    btnStart.Enabled      = false;
                    btnStopRecord.Enabled = true;
                }
                catch (Exception ex)
                {
                    Log.Debug("DEBUG", ex.Message);
                }
                Toast.MakeText(this, "Recording...", ToastLength.Short).Show();
            }
        }
Exemplo n.º 4
0
        public Task RecordAsync()
        {
            if (isRecording)
            {
                return(Task.CompletedTask);
            }

            isRecording = true;

            audioFilePath = Path.Combine("/sdcard/", Path.GetTempFileName());

            mediaRecorder.SetAudioSource(AudioSource.Mic);
            mediaRecorder.SetOutputFormat(OutputFormat.Mpeg4);
            mediaRecorder.SetAudioEncoder(AudioEncoder.Aac);
            mediaRecorder.SetOutputFile(audioFilePath);
            mediaRecorder.Prepare();
            mediaRecorder.Start();

            return(Task.CompletedTask);
        }
Exemplo n.º 5
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.º 6
0
        public void Record()
        {
            try
            {
                //Java.IO.File sdDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
                //filePath = sdDir + "/" + "testAudio.mp3";
                if (!Directory.Exists(storyPath))
                {
                    Directory.CreateDirectory(storyPath);
                }

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

                //Java.IO.File myFile = new Java.IO.File(filePath);
                //myFile.CreateNewFile();

                if (recorder == null)
                {
                    recorder = new MediaRecorder(); // Initial state.
                }
                else
                {
                    recorder.Reset();
                }

                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.Mpeg4);
                recorder.SetAudioEncoder(AudioEncoder.AmrNb); // Initialized state.
                recorder.SetOutputFile(currentFilePath);      // DataSourceConfigured state.
                recorder.Prepare();                           // Prepared state
                recorder.Start();                             // Recording state.
                IsStopped = false;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
            }
        }
        private void OnVideoSessionConfigured(CameraCaptureSession session)
        {
            var recordRequestBuilder = cameraDevice.CreateCaptureRequest(CameraTemplate.Preview);

            recordRequestBuilder.AddTarget(previewSurface);
            recordRequestBuilder.AddTarget(mediaRecorder.Surface);

            var availableAutoFocusModes = (int[])characteristics.Get(CameraCharacteristics.ControlAfAvailableModes);

            if (availableAutoFocusModes.Any(afMode => afMode == (int)ControlAFMode.ContinuousVideo))
            {
                previewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousVideo);
            }

            captureSession.Close();
            captureSession = session;
            captureSession.SetRepeatingRequest(recordRequestBuilder.Build(), null, null);

            mediaRecorder.Start();
            isRecording = true;
        }
Exemplo n.º 8
0
        public void Start()
        {
            if (IsRecording)
            {
                return;
            }

            _lastRecordFullpath = GenerateTempFilepath();

            _recorder.Reset();
            _recorder.SetAudioSource(AudioSource.Mic);
            _recorder.SetOutputFormat(OutputFormat.ThreeGpp);
            _recorder.SetAudioEncoder(AudioEncoder.AmrWb);
            _recorder.SetOutputFile(_lastRecordFullpath);
            _recorder.Prepare();
            _recorder.Start();

            _lastRecordStartTime = DateTime.Now;

            IsRecording = true;
        }
Exemplo n.º 9
0
        public static void ActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == REQUEST_RECORD)
            {
                if (resultCode == Result.Ok)
                {
                    mediaProjection = mediaProjectionManager.GetMediaProjection((int)resultCode, data);
                    mediaProjection.RegisterCallback(new MediaProjectionCallback(), null);

                    // DisplayManager.VirtualDisplayFlagAutoMirror,
                    virtualDisplay = mediaProjection.CreateVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, (int)screenDensity,
                                                                          DisplayFlags.Presentation, mediaRecorder.Surface, null, null);

                    mediaRecorder.Start();
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("!!Result Code Is" + resultCode + "!!");
                }
            }
        }
Exemplo n.º 10
0
        public static Task StartRecording(OnError errorAction = OnError.Toast)
        {
            try
            {
                if (Recording?.Exists() == true)
                {
                    lock (Recording.GetSyncLock())
                        Recording.Delete();
                }

                var newFile = $"Myfile{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.wav";
                Recording = IO.CreateTempDirectory().GetFile(newFile);
                lock (Recording.GetSyncLock())
                    Recording.Delete();

                CreateRecorder();
                Recorder.Start();
                return(Task.CompletedTask);
            }
            catch (Exception ex) { return(errorAction.Apply(ex)); }
        }
Exemplo n.º 11
0
 void SetupEventHandlers()
 {
     //capturePhotoButton
     captureButton.Click += async(sender, e) =>
     {
         if (isVideoStarted == false)
         {
             isVideoStarted           = true;
             captureButton.Background = Resources.GetDrawable(Resource.Drawable.captureButton_red);
             recorder.Start();
             //---------------------------------------------------------------
             timer.Base       = SystemClock.ElapsedRealtime();
             timer.Visibility = ViewStates.Visible;
             timer.Start();
         }
         else
         {
             StopRecording();
         }
     };
 }
Exemplo n.º 12
0
        public static void Start(string fileName)
        {
            if (_mic != null)
            {
                Stop();
            }
            _mic = new MediaRecorder();

            // set some default values for recording settings
            _mic.SetAudioSource(AudioSource.Mic);
            _mic.SetOutputFormat(OutputFormat.ThreeGpp);
            _mic.SetAudioEncoder(AudioEncoder.AmrNb);

            // define a filename and location for the output file
            Device.File.EnsureDirectoryExistsForFile(fileName);
            _mic.SetOutputFile(fileName);

            // prepare and start recording
            _mic.Prepare();
            _mic.Start();
        }
Exemplo n.º 13
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 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.º 15
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            MediaRecorder recorder = null;

            try
            {
                if (SensusServiceHelper.Get().ObtainPermission(Permission.Microphone) != PermissionStatus.Granted)
                {
                    throw new Exception("Cannot access microphone.");
                }

                recorder = new MediaRecorder();
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                recorder.SetOutputFile("/dev/null");
                recorder.Prepare();
                recorder.Start();

                // mark start time of amplitude measurement -- MaxAmplitude is always computed from previous call to MaxAmplitude
                int dummy = recorder.MaxAmplitude;

                Thread.Sleep(SampleLengthMS);

                return(new Datum[] { new SoundDatum(DateTimeOffset.UtcNow, 20 * Math.Log10(recorder.MaxAmplitude)) });  // http://www.mathworks.com/help/signal/ref/mag2db.html
            }
            finally
            {
                if (recorder != null)
                {
                    try { recorder.Stop(); }
                    catch (Exception) { }

                    try { recorder.Release(); }
                    catch (Exception) { }
                }
            }
        }
        public Task RecordAsync()
        {
            if (isRecording)
            {
                return(Task.CompletedTask);
            }

            return(Task.Run(() =>
            {
                try
                {
                    isRecording = true;
                    filePath = Path.GetTempFileName();

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

                    recorder = new MediaRecorder();

                    recorder.Reset();
                    recorder.SetAudioSource(AudioSource.Mic);
                    recorder.SetOutputFormat(OutputFormat.AacAdts);
                    recorder.SetAudioEncoder(AudioEncoder.Aac);
                    recorder.SetAudioEncodingBitRate(32000);
                    recorder.SetAudioSamplingRate(44100);
                    recorder.SetOutputFile(filePath);
                    recorder.Prepare();
                    recorder.Start();
                }
                catch (Exception e)
                {
                    isRecording = false;
                    Console.Out.WriteLine(e.StackTrace);
                }
            }));
        }
Exemplo n.º 17
0
        private void RecordAudio()
        {
            if (isGrantedPermission)
            {
                string path = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/hello.txt";

                using (var streamWriter = new StreamWriter(path, true))
                {
                    streamWriter.WriteLine(DateTime.UtcNow);
                }

                using (var streamReader = new StreamReader(path))
                {
                    string content = streamReader.ReadToEnd();
                    System.Diagnostics.Debug.WriteLine(content);
                }



                pathSave = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/_audio.3gp";
                //pathSave = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + new Guid().ToString() + "_audio.3gp";

                SetUpMediaRecorder();
                try
                {
                    mediaRecorder.Prepare();
                    mediaRecorder.Start();

                    btnRecord.Enabled     = false;
                    btnStopRecord.Enabled = true;
                }
                catch (Exception ex)
                {
                    Log.Debug("DEBUG", ex.Message);
                }
                Toast.MakeText(this, "Recording...", ToastLength.Short).Show();
            }
        }
Exemplo n.º 18
0
        protected override IEnumerable <SensusService.Datum> Poll()
        {
            MediaRecorder recorder = null;

            try
            {
                recorder = new MediaRecorder();
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                recorder.SetOutputFile("/dev/null");
                recorder.Prepare();
                recorder.Start();

                // mark start time of amplitude measurement -- see documentation for MaxAmplitude
                int dummy = recorder.MaxAmplitude;

                Thread.Sleep(_sampleLengthMS);

                return(new Datum[] { new SoundDatum(DateTimeOffset.UtcNow, 20 * Math.Log10(recorder.MaxAmplitude)) });  // http://www.mathworks.com/help/signal/ref/mag2db.html
            }
            catch (Exception)
            {
                // exception might be thrown if we're doing voice recognition concurrently
                return(new Datum[] { });
            }
            finally
            {
                if (recorder != null)
                {
                    try { recorder.Stop(); }
                    catch (Exception) { }

                    try { recorder.Release(); }
                    catch (Exception) { }
                }
            }
        }
Exemplo n.º 19
0
        public bool StartRecording(string pathFile, out string message)
        {
            bool result = true;

            message = null;

            try {
                InitRecorder();

                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                _recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                _recorder.SetOutputFile(pathFile);
                _recorder.Prepare();
                _recorder.Start();
            } catch (Exception ex) {
                result  = false;
                message = string.Format("Unable to start recording audio. Error: {0}", ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }

            return(result);
        }
        private void StartRecording(int count)
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            path = Path.Combine(path, "myfile" + count + ".amr");

            if (count > 0)
            {
                _recorder.Stop();
                _recorder.Reset();
            }

            _recorder.SetOutputFile(path);

            _recorder.SetAudioSource(AudioSource.Mic);
            _recorder.SetOutputFormat(OutputFormat.AmrWb);
            _recorder.SetAudioEncoder(AudioEncoder.AmrWb);
            _recorder.SetAudioEncodingBitRate(16000);
            _recorder.SetAudioChannels(1);

            _recorder.Prepare();
            _recorder.Start();
        }
Exemplo n.º 21
0
        public void StartRecording(int id)
        {
            try
            {
                if (File.Exists(Constants.INITIAL_AUDIO_FILE_PATH))
                {
                    File.Delete(Constants.INITIAL_AUDIO_FILE_PATH);
                }

                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.Mpeg4);
                _recorder.SetAudioEncoder(AudioEncoder.Aac);
                _recorder.SetOutputFile(Constants.INITIAL_AUDIO_FILE_PATH);
                _recorder.Prepare();
                _recorder.Start();
            }

            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
                throw;
            }
        }
Exemplo n.º 22
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AudioRecorder);
            start = FindViewById <Button>(Resource.Id.start);
            stop  = FindViewById <Button>(Resource.Id.stop);

            string path = "/sdcard/test.3gpp";

            start.Click += delegate {
                stop.Enabled  = !stop.Enabled;
                start.Enabled = !start.Enabled;

                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                recorder.SetOutputFile(path);
                recorder.Prepare();
                recorder.Start();
            };

            stop.Click += delegate {
                stop.Enabled = !stop.Enabled;

                recorder.Stop();
                recorder.Reset();

                player.SetDataSource(path);
                player.Prepare();
                player.Start();
            };



            // Create your application here
        }
Exemplo n.º 23
0
        void NewRecord(object sender, EventArgs e)
        {
            try
            {
                if (IsAllPermissionEnabled())
                {
                    _ = System.IO.Directory.CreateDirectory($"{Android.OS.Environment.ExternalStorageDirectory.AbsolutePath}/Ynote/Audio");

                    RecordedAudioPath = $"{$"{Android.OS.Environment.ExternalStorageDirectory.AbsolutePath}/Ynote/Audio"}{$"/record{new SQLiteConnection(CONNECTION.DBPath).Table<Note>().Count() + 1.ToString()}.mp3"}";
                    PrepareSetup();
                    MediaRecorder.Prepare();
                    MediaRecorder.Start();
                    FindViewById <Button>(Resource.Id.btnRecordingAction).Text = "Recording...";

                    FindViewById <Button>(Resource.Id.btnRecordingAction).SetCompoundDrawablesWithIntrinsicBounds(_ = GetDrawable(Resource.Drawable.icon_mic_active), null, null, null);
                    FindViewById <Button>(Resource.Id.btnRecordingAction).SetTextColor(Android.Graphics.Color.ParseColor("#55cf90"));
                    FindViewById <Button>(Resource.Id.btnRecordingAction).SetTypeface(FindViewById <Button>(Resource.Id.btnRecordingAction).Typeface, Android.Graphics.TypefaceStyle.Italic);
                    Toast.MakeText(this, "Click save to when you are done", ToastLength.Short).Show();
                }
                else
                {
                    Snackbar.Make(FindViewById <LinearLayout>(Resource.Id.newnotelinear),
                                  "Ynote is requesting Mic and Storage permission to use this feature.",
                                  Snackbar.LengthIndefinite)
                    .SetAction(Android.Resource.String.Ok,
                               new Action <View>(delegate(View obj) {
                        ActivityCompat.RequestPermissions(this, requiredPermissions, 1000);
                    }
                                                 )
                               ).Show();
                }
            }
            catch (Exception ee)
            {
                Toast.MakeText(this, ee.Message, ToastLength.Short).Show();
            }
        }
Exemplo n.º 24
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.º 25
0
        //public IntPtr Handle => throw new NotImplementedException();

        //static string filePath = Android.OS.Environment.ExternalStorageDirectory + "/" + Android.OS.Environment.DirectoryMusic + "/testAudio.amr";

        public void Start(string filePath)
        {
            try
            {
                //Java.IO.File sdDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
                //filePath = sdDir + "/" + "testAudio.mp3";
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                //Java.IO.File myFile = new Java.IO.File(filePath);
                //myFile.CreateNewFile();

                if (recorder == null)
                {
                    recorder = new MediaRecorder(); // Initial state.
                }
                else
                {
                    recorder.Reset(); //录音重置
                }
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.AmrWb); //设置输出格式
                recorder.SetAudioEncoder(AudioEncoder.AmrWb); //设置编码器
                recorder.SetAudioSamplingRate(16000);         //设置采样率
                recorder.SetOutputFile(filePath);             //保存路径

                recorder.Prepare();                           // 录音准备-固定顺序
                recorder.Start();                             // 录音开始-固定顺序
            }
            catch (System.Exception ex)
            {
                Toast.MakeText(Android.App.Application.Context, ex.Message, ToastLength.Long).Show();
            }
        }
        public Task StartRecording()
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                recorder = new MediaRecorder();
                recorder.SetAudioSource(AudioSource.Mic);
                recorder.SetOutputFormat(OutputFormat.Mpeg4);
                recorder.SetAudioEncoder(AudioEncoder.Aac);
                recorder.SetOutputFile(filePath);
                recorder.Prepare();
                recorder.Start();

                WatchDuration();
            }
            catch (Exception ex)
            {
                EbLog.Error(ex.Message);
            }
            return(Task.FromResult(false));
        }
Exemplo n.º 27
0
        public void StartRecord()
        {
            try
            {
                string sFilePath = AudioFilePath + "/" + AudioFileName + ".mp4";

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

                if (Recorder == null)
                {
                    Recorder = new MediaRecorder();
                }

                Recorder.Reset();
                Recorder.SetAudioSource(AudioSource.Mic);
                Recorder.SetOutputFormat(OutputFormat.Mpeg4);
                Recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                Recorder.SetOutputFile(sFilePath);
                Recorder.Prepare();
                Recorder.Start();
            }
            catch { }

            /*
             * Recorder.SetAudioSource(AudioSource.Mic);
             * Recorder.SetOutputFormat(OutputFormat.ThreeGpp);
             * Recorder.SetAudioEncoder(AudioEncoder.AmrNb);
             *
             * Recorder.SetOutputFile(AudioFilePath + "/" + AudioFileName + ".wav");
             * Recorder.Prepare();
             * Recorder.Start();
             */
        }
Exemplo n.º 28
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.º 29
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.º 30
0
        //.............................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();
            };
        }