コード例 #1
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            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 -- 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
            }
            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) { }
                }
            }
        }
コード例 #2
0
ファイル: AndroidSoundProbe.cs プロジェクト: scooter7/sensus
        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);
                }
            }));
        }
コード例 #4
0
        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();
        }
コード例 #5
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;
            }
        }
コード例 #6
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);
        }
コード例 #7
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();
            }
        }
コード例 #8
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
        }
コード例 #9
0
        private void StartRecordingObject()
        {
            try
            {
                ActivityCompat.RequestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
                    );

                string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
                mMediaRecorder.SetVideoSource(VideoSource.Surface);
                mMediaRecorder.SetOutputFormat(OutputFormat.Webm);
                //mMediaRecorder.SetVideoEncodingBitRate(512 * 1000);
                mMediaRecorder.SetVideoEncoder(VideoEncoder.Vp8);
                mMediaRecorder.SetVideoSize(1280, 720);
                //mMediaRecorder.SetVideoFrameRate(10);
                mMediaRecorder.SetOutputFile(path);
                mMediaRecorder.Prepare();
            }
            catch (Exception e)
            {
            }
        }
コード例 #10
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();
            }
        }
コード例 #11
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();
             */
        }
コード例 #12
0
ファイル: ACamera.cs プロジェクト: joaofiliperocha/Auget
        //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;
        }
コード例 #13
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);
        }
コード例 #14
0
        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));
        }
コード例 #15
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();
            };
        }
コード例 #16
0
        /**
         * Records a short sample of AAC ADTS from the microphone to find out what the sampling rate really is
         * On some phone indeed, no error will be reported if the sampling rate used differs from the
         * one selected with setAudioSamplingRate
         * @throws IOException
         * @throws IllegalStateException
         */

        private void testADTS()
        {
            setAudioEncoder((int)Android.Media.AudioEncoder.Aac);
            try
            {
                Type mType = typeof(MediaRecorder.OutputFormat);

                if (mType.GetField("AAC_ADTS") == null)
                {
                    return;
                }

                setOutputFormat((int)Android.Media.AudioEncoder.Aac);
            }
            catch (System.Exception ignore)
            {
                setOutputFormat(6);
            }

            System.String key = PREF_PREFIX + "aac-" + mQuality.samplingRate;

            if (mSettings != null && mSettings.Contains(key))
            {
                System.String[] s = mSettings.GetString(key, "").Split(',');
                mQuality.samplingRate = (int)Integer.ValueOf(s[0]);
                mConfig  = (int)Integer.ValueOf(s[1]);
                mChannel = (int)Integer.ValueOf(s[2]);
                return;
            }

            System.String TESTFILE = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/spydroid-test.adts";

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

            // The structure of an ADTS packet is described here: http://wiki.multimedia.cx/index.php?title=ADTS

            // ADTS header is 7 or 9 bytes long
            byte[] buffer = new byte[9];

            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.SetAudioSource((AudioSource)mAudioSource);
            mMediaRecorder.SetOutputFormat((OutputFormat)mOutputFormat);
            mMediaRecorder.SetAudioEncoder((AudioEncoder)mAudioEncoder);
            mMediaRecorder.SetAudioChannels(1);
            mMediaRecorder.SetAudioSamplingRate(mQuality.samplingRate);
            mMediaRecorder.SetAudioEncodingBitRate(mQuality.bitRate);
            mMediaRecorder.SetOutputFile(TESTFILE);
            mMediaRecorder.SetMaxDuration(1000);
            mMediaRecorder.Prepare();
            mMediaRecorder.Start();

            // We record for 1 sec
            // TODO: use the MediaRecorder.OnInfoListener
            try
            {
                Thread.Sleep(2000);
            }
            catch (InterruptedException e) { }

            mMediaRecorder.Stop();
            mMediaRecorder.Release();
            mMediaRecorder = null;

            File             file = new File(TESTFILE);
            RandomAccessFile raf  = new RandomAccessFile(file, "r");

            // ADTS packets start with a sync word: 12bits set to 1
            while (true)
            {
                if ((raf.ReadByte() & 0xFF) == 0xFF)
                {
                    buffer[0] = (byte)raf.ReadByte();
                    if ((buffer[0] & 0xF0) == 0xF0)
                    {
                        break;
                    }
                }
            }

            raf.Read(buffer, 1, 5);

            mSamplingRateIndex    = (buffer[1] & 0x3C) >> 2;
            mProfile              = ((buffer[1] & 0xC0) >> 6) + 1;
            mChannel              = (buffer[1] & 0x01) << 2 | (buffer[2] & 0xC0) >> 6;
            mQuality.samplingRate = AUDIO_SAMPLING_RATES[mSamplingRateIndex];

            // 5 bits for the object type / 4 bits for the sampling rate / 4 bits for the channel / padding
            mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;

            Log.Info(TAG, "MPEG VERSION: " + ((buffer[0] & 0x08) >> 3));
            Log.Info(TAG, "PROTECTION: " + (buffer[0] & 0x01));
            Log.Info(TAG, "PROFILE: " + AUDIO_OBJECT_TYPES[mProfile]);
            Log.Info(TAG, "SAMPLING FREQUENCY: " + mQuality.samplingRate);
            Log.Info(TAG, "CHANNEL: " + mChannel);

            raf.Close();

            if (mSettings != null)
            {
                ISharedPreferencesEditor editor = mSettings.Edit();
                editor.PutString(key, mQuality.samplingRate + "," + mConfig + "," + mChannel);
                editor.Commit();
            }

            if (!file.Delete())
            {
                Log.Error(TAG, "Temp file could not be erased");
            }
        }
コード例 #17
0
        public void Start(bool microphoneEnabled)
        {
            if (IsRunning)
            {
                return;
            }

            IsRunning = !IsRunning;

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

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

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


            var message = "";

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

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

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

                mediaRecorder.Prepare();

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

                message = "go to ActivityResult method";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                RecordStart?.Invoke(this, new ErrorEventArgs(message));
            }
        }
コード例 #18
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);
                }
            }
        }
コード例 #19
0
        //     public string path = "C:/Users/mof1/Source/Repos/Natural Domain Specific Speech Synthesis Framework/NDSSSF.Mobile/NDSSSF.Droid/Recordings/";
        // public string Path="";

        protected override void OnCreate(Bundle bundle)
        {
            // string path = "C:/Users/mof1/Documents/Visual Studio 2015/Projects/NDSSF/NDSSF/recordings/test.3gpp";
            System.Diagnostics.Debug.Write("------------------------->OnCreate()");
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.AD2);
            EditText word_text1 = FindViewById <EditText>(Resource.Id.user_ID);

            word_text1.Click += delegate { Toast.MakeText(this, "Only Enter Alphabets", ToastLength.Short).Show(); };
            EditText word_text2 = FindViewById <EditText>(Resource.Id.password);

            word_text2.Click += delegate { Toast.MakeText(this, "Only Enter Alphabets", ToastLength.Short).Show(); };

            Spinner spinner = FindViewById <Spinner>(Resource.Id.spinner1);

            spinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected);
            var adapter = ArrayAdapter.CreateFromResource(
                this, Resource.Array.type_array, Android.Resource.Layout.SimpleSpinnerItem);

            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;


            //   spinner.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, example);


            ImageButton Save = FindViewById <ImageButton>(Resource.Id.imageButton3);

            //   TextView setcolor = FindViewById<TextView>(Resource.Id.wordtype);

            Save.Click += async delegate
            {
                Word word = new Word();
                switch (spinner.SelectedItemPosition)
                {
                case 0:
                    word.Type = Types.Noun;
                    // setcolor.SetTextColor(color:#FF0000);

                    break;

                case 1:
                    word.Type = Types.Verb;
                    break;

                case 2:
                    word.Type = Types.Adjective;
                    break;

                case 3:
                    word.Type = Types.Pronoun;
                    break;

                case 4:
                    word.Type = Types.Preposition;
                    break;

                case 5:
                    word.Type = Types.Adverb;
                    break;

                default:

                    break;
                }


                //Adding here

                word.Text = word_text1.Text;
                //    word.Type = Types.Noun;
                word.Tone  = word_text2.Text;
                word.Audio = dir.AbsoluteFile.ToString();

                await DataRepository.Words.Add(word);

                Toast.MakeText(this, word.Text.ToString() + " Saved!", ToastLength.Short).Show();
                StartActivity(typeof(Audio1));
                //  StartActivity(typeof(STE5_Layout));
                // nitems.Add((await DataRepository.Words.GetAll()).FirstOrDefault()?.Text);


                // w.Type = example;
            };



            String path = dir.Path;

            _start        = FindViewById <ImageButton>(Resource.Id.imageButton1);
            _stop         = FindViewById <ImageButton>(Resource.Id.imageButton2);
            _start.Click += delegate { //audio recording
                _stop.Enabled  = !_stop.Enabled;
                _start.Enabled = !_start.Enabled;



                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                _recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                _recorder.SetAudioChannels(1);
                // _recorder.setAudioSamplingRate(8000);

                _recorder.SetOutputFile(dir.Path);
                _recorder.Prepare();
                _recorder.Start();
            };

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

                _recorder.Stop();
                _recorder.Reset();

                _player.SetDataSource(dir.Path);

                _player.Prepare();
                _player.Start();
            };
        }
コード例 #20
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)
            {
            }
        }
コード例 #21
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;

	    }
コード例 #22
0
        //public string Path="";

        protected override void OnCreate(Bundle bundle)
        {
            // string path = "C:/Users/mof1/Documents/Visual Studio 2015/Projects/NDSSF/NDSSF/recordings/test.3gpp";
            System.Diagnostics.Debug.Write("------------------------->OnCreate()");
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.STE2);
            EditText word_text2 = FindViewById <EditText>(Resource.Id.sentence_ID);

            word_text2.Click += delegate { Toast.MakeText(this, "Only Enter Alphabets", ToastLength.Short).Show(); };
            ImageButton Save = FindViewById <ImageButton>(Resource.Id.imageButtonsave);

            Save.Click += async delegate
            {
                Sentence s = new Sentence();
                s.Text  = word_text2.Text;
                s.Audio = dir.AbsoluteFile.ToString();

                await DataRepository.Sentences.Add(s);

                Toast.MakeText(this, s.Text.ToString() + " Saved!", ToastLength.Short).Show();
                StartActivity(typeof(STE1));
            };

            String path = dir.Path;

            _start        = FindViewById <ImageButton>(Resource.Id.imageButton1);
            _stop         = FindViewById <ImageButton>(Resource.Id.imageButton2);
            _start.Click += delegate { //audio recording
                _stop.Enabled  = !_stop.Enabled;
                _start.Enabled = !_start.Enabled;



                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                _recorder.SetAudioEncoder(AudioEncoder.AmrNb);
                _recorder.SetAudioChannels(1);
                // _recorder.setAudioSamplingRate(8000);

                _recorder.SetOutputFile(dir.Path);
                _recorder.Prepare();
                _recorder.Start();
            };

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

                _recorder.Stop();
                _recorder.Reset();

                _player.SetDataSource(dir.Path);

                _player.Prepare();
                _player.Start();
            };



            ImageButton next = FindViewById <ImageButton>(Resource.Id.imageButton5);

            next.Click += simpleDailogueClick;

            //  SetContentView(Resource.Layout.STE2);
        }
コード例 #23
0
        //Used for entering the Mandarin_ma speech processing screen
        void HandleMandarin_Ma_Male_Select()
        {
            SetContentView(Resource.Layout.Mandarin_Mother_Male);

            string RecordPath = "/sdcard/Recording.mp3";
            //string RecordPath = Environment.getExternalStorageDirectory ()
            //	.getAbsolutePath () + "/Recording.mp3";


            //string RecordPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Recording.3gpp";
            //string RecordPath = this.file.getAbsolutePath().substring(8)


            Button PlayStock = FindViewById <Button> (Resource.Id.PlayMa);

            PlayBack = FindViewById <Button> (Resource.Id.PlayBack);
            Button BackToMandarin = FindViewById <Button> (Resource.Id.BackToMandarin);

            RecordVoice = FindViewById <Button> (Resource.Id.Record);
            StopRecord  = FindViewById <Button> (Resource.Id.Stop);
            StockPlayer = MediaPlayer.Create(this, Resource.Raw.mother);

            _recorder = new MediaRecorder();
            _player   = new MediaPlayer();



            //Click Event Handlers
            PlayStock.Click += delegate {
                StockPlayer.Start();
            };


            RecordVoice.Click += delegate {
                RecordVoice.Enabled = !RecordVoice.Enabled;
                StopRecord.Enabled  = !StopRecord.Enabled;
                if (PlayBack.Enabled == true)
                {
                    PlayBack.Enabled = false;
                }


                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.Mpeg4);
                _recorder.SetOutputFile(RecordPath);
                _recorder.SetAudioEncoder(AudioEncoder.Aac);


                _recorder.Prepare();
                _recorder.Start();
            };


            //Stops recording
            StopRecord.Click += delegate {
                StopRecord.Enabled = !StopRecord.Enabled;

                if (PlayBack.Enabled == false)
                {
                    PlayBack.Enabled = true;
                }


                _recorder.Stop();
                _recorder.Reset();

                /* For instant playback
                 * _player.SetDataSource (RecordPath);
                 * _player.Prepare ();
                 * _player.Start ();
                 */
                RecordVoice.Enabled = !RecordVoice.Enabled;
            };


            PlayBack.Click += delegate {
                RecordPlayer = new MediaPlayer();
                RecordPlayer.SetDataSource(RecordPath);
                RecordPlayer.Prepare();
                RecordPlayer.Start();
            };


            BackToMandarin.Click += delegate {
                HandleMandarinSelect();
            };
        }
コード例 #24
0
        private void RecordAudioButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (_recordAudioLabel.Text == GetString(Resource.String.recordAudioLabelReady))
                {
                    if (_recordAudioButton != null)
                    {
                        _recordAudioButton.Text = GetString(Resource.String.recordAudioButtonStop);
                    }

                    if (_recordAudioLabel != null)
                    {
                        _recordAudioLabel.Text = GetString(Resource.String.recordAudioLabelRecording);
                    }


                    //recorder.Stop();

                    // file path
                    string path = Activity.BaseContext.FilesDir.AbsolutePath;
                    if (!string.IsNullOrEmpty(path))
                    {
                        _filePath = path + "/voice_" + DateTime.Now.Day.ToString() +
                                    "_" + DateTime.Now.Month.ToString() +
                                    "_" + DateTime.Now.Year.ToString() +
                                    "_" + DateTime.Now.Hour.ToString() +
                                    "_" + DateTime.Now.Minute.ToString() +
                                    "_" + DateTime.Now.Second.ToString() +
                                    "_" + DateTime.Now.Millisecond.ToString() + ".3gpp";
                        Log.Info(TAG, "RecordAudioButton_Click: Full file and Path - '" + _filePath.Trim() + "'");

                        _isRecording = true;

                        Log.Info(TAG, "RecordAudioButton_Click: Recording Audio...");
                        SetControlsOnRecordingStateChange();
                        _mediaRecorder.SetAudioSource(AudioSource.Mic);
                        _mediaRecorder.SetOutputFormat(OutputFormat.ThreeGpp);
                        _mediaRecorder.SetAudioEncoder(AudioEncoder.AmrNb);
                        _mediaRecorder.SetOutputFile(_filePath.Trim());
                        _mediaRecorder.Prepare();
                        _mediaRecorder.Start();
                        Log.Info(TAG, "RecordAudioButton_Click: Start called on MediaRecorder...");
                    }
                    return;
                }

                if (_recordAudioLabel.Text == GetString(Resource.String.recordAudioLabelRecording))
                {
                    if (_recordAudioLabel != null)
                    {
                        _recordAudioLabel.Text = GetString(Resource.String.recordAudioLabelReady);
                    }
                    if (_recordAudioButton != null)
                    {
                        _recordAudioButton.Text = GetString(Resource.String.recordAudioButtonRecord);
                    }
                    Log.Info(TAG, "RecordAudioButton_Click: Attempting to stop recording...");
                    _mediaRecorder.Stop();
                    _mediaRecorder.Reset();
                    _mediaRecorder.Release();
                    Log.Info(TAG, "RecordAudioButton_Click: Successfully stopped MediaRecorder");
                    _isRecording = false;
                    _hasRecorded = true;

                    SetControlsOnRecordingStateChange();
                }
            }
            catch (Exception ex)
            {
                Log.Error(TAG, "RecordAudioButton_Click: Exception - " + ex.Message);
                if (Activity != null)
                {
                    if (GlobalData.ShowErrorDialog)
                    {
                        ErrorDisplay.ShowErrorAlert(Activity, ex, Activity.GetString(Resource.String.ErrorAddingVoiceRecording), "VoiceRecordingDialogFragment.RecordAudioButton_Click");
                    }
                }
            }
        }
コード例 #25
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);
        }
コード例 #26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Song);

            Songs  songs     = new Songs();
            int    songIndex = Intent.GetIntExtra("songIndex", 0);
            string song      = songs.GetSong(songIndex);

            StartSong(song);

            ImageButton backButton   = (ImageButton)FindViewById <ImageButton>(Resource.Id.back);
            ImageButton prevButton   = (ImageButton)FindViewById <ImageButton>(Resource.Id.prevSong);
            ImageButton playButton   = (ImageButton)FindViewById <ImageButton>(Resource.Id.play);
            ImageButton nextButton   = (ImageButton)FindViewById <ImageButton>(Resource.Id.nextSong);
            ImageButton stopButton   = (ImageButton)FindViewById <ImageButton>(Resource.Id.stop);
            ImageButton pauseButton  = (ImageButton)FindViewById <ImageButton>(Resource.Id.pause);
            ImageButton recordButton = (ImageButton)FindViewById <ImageButton>(Resource.Id.record);

            prevButton.LongClick += delegate
            {
                StartSong(songs.GetSong(0));
            };

            prevButton.Click += delegate
            {
                if (songIndex != 0)
                {
                    song       = songs.GetSong(songIndex - 1);
                    songIndex -= 1;
                    StartSong(song);
                }
            };

            playButton.Click += delegate
            {
                if (isPaused)
                {
                    mediaPlayer.Start();
                }
                if (isStopped)
                {
                    StartSong(songs.GetSong(songIndex));
                }
                isPaused  = false;
                isStopped = false;
            };

            nextButton.Click += delegate
            {
                if (songIndex != 2)
                {
                    song       = songs.GetSong(songIndex + 1);
                    songIndex += 1;
                    StartSong(song);
                }
            };

            nextButton.LongClick += delegate
            {
                StartSong(songs.GetSong(2));
            };

            stopButton.Click += delegate
            {
                if (mediaPlayer.IsPlaying)
                {
                    mediaPlayer.Stop();
                }
                isStopped = true;
            };

            pauseButton.Click += delegate
            {
                if (mediaPlayer.IsPlaying)
                {
                    mediaPlayer.Pause();
                }
                isPaused = true;
            };

            recordButton.Click += delegate
            {
                if (mediaPlayer.IsPlaying)
                {
                    if (!isRecording)
                    {
                        recordButton.BackgroundTintList = GetColorStateList(Resource.Color.red);
                        mediaRecorder = new MediaRecorder();
                        isRecording   = true;
                        mediaRecorder.SetAudioSource(AudioSource.Mic);
                        mediaRecorder.SetOutputFormat(OutputFormat.ThreeGpp);
                        mediaRecorder.SetOutputFile(Android.OS.Environment.ExternalStorageDirectory + "/" + song + ".3gp");
                        mediaRecorder.SetAudioEncoder(AudioEncoder.AmrNb);
                        mediaRecorder.Prepare();
                        mediaRecorder.Start();
                    }
                    else
                    {
                        isRecording = false;

                        try
                        {
                            mediaRecorder.Stop();
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }

                        mediaRecorder.Release();
                        mediaRecorder = null;
                    }
                }
            };

            backButton.Click += delegate
            {
                mediaPlayer.Release();
                StartActivity(new Intent(this, typeof(MainActivity)));
            };
        }
コード例 #27
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();
             * };*/
        }
コード例 #28
0
ファイル: MainActivity.cs プロジェクト: Sablayrolles/HiveMind
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            // Get the button "Record"
            Button buttonRec = FindViewById <Button>(Resource.Id.buttonRec1);
            // Get the button "Stop"
            Button buttonStop = FindViewById <Button>(Resource.Id.buttonStop1);
            // Get the Seek Bar
            SeekBar seek = FindViewById <SeekBar>(Resource.Id.seekBar1);
            // Get the TextView where we display the Seek Bar information
            TextView displaySec = FindViewById <TextView>(Resource.Id.textView1);
            // Get the text field to enter the file name
            EditText fileName = FindViewById <EditText>(Resource.Id.editText1);
            // Get the chronometer
            Chronometer chrono = FindViewById <Chronometer>(Resource.Id.chronometer1);
            // Create a media recorder
            MediaRecorder recorder = new MediaRecorder();
            // Create the path where the audio file will be written
            string storage_path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
            // Incremental variable for each sound files
            int i;

            // Display seconds when the value of the seekbar change
            seek.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => {
                if (e.FromUser)
                {
                    displaySec.Text = string.Format("{0} seconds", e.Progress + 1);
                }
            };

            // Function on click button start
            buttonRec.Click += delegate {
                // Create new timer
                timer = new Timer();
                // Set the variable to increment file name to 1
                i = 0;
                // Disable editText
                fileName.Enabled = false;
                // Disable seekbar
                seek.Enabled = false;
                // Set the timer
                timer.Interval = (seek.Progress + 1) * 1000;
                timer.Elapsed += timerElapsed;
                timer.Start();
                // Chronometer
                chronoStartProp();
                // Audio record
                startAudioRecord(i);
            };

            // Function on click button stop
            buttonStop.Click += delegate {
                // Enable the file name text edit
                fileName.Enabled = true;
                // Enable seekbar
                seek.Enabled = true;
                // Kill the timer
                timer.Dispose();
                timer = null;
                // Chronometer
                chronoStopProp();
                // Audio record
                stopAudioRecord();
            };

            // Start chronometer and change its properties
            void chronoStartProp()
            {
                // Show the chrono
                chrono.Visibility = Android.Views.ViewStates.Visible;
                // Disable button rec
                buttonRec.Enabled = false;
                // Enable button stop
                buttonStop.Enabled = true;
                // Start the chronometer
                chrono.Base = SystemClock.ElapsedRealtime();
                chrono.Start();
            }

            // Stop chronometer and change its properties
            void chronoStopProp()
            {
                chrono.Stop();
                chrono.Visibility  = Android.Views.ViewStates.Invisible;
                buttonStop.Enabled = false;
                buttonRec.Enabled  = true;
            }

            // Start audio record
            void startAudioRecord(int nb)
            {
                string f_path;

                f_path = storage_path + "/music/" + fileName.Text + nb + ".3gpp";

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

            // Stop audio record
            void stopAudioRecord()
            {
                recorder.Stop();
                recorder.Reset();
            }

            // Function which is running each x seconds, where x is the number chosen by the user
            void timerElapsed(object sender, ElapsedEventArgs e)
            {
                stopAudioRecord();
                i++;
                startAudioRecord(i);
            }
        }
コード例 #29
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_third);
            // Create your application here

            bckButton1       = FindViewById <Button>(Resource.Id.bckButton1);
            strtRecordButton = FindViewById <Button>(Resource.Id.strtRecordButton);
            stpRecordButton  = FindViewById <Button>(Resource.Id.stpRecordButton);

            // Run-time Permission
            if (CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted &&
                CheckSelfPermission(Manifest.Permission.RecordAudio) != Android.Content.PM.Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[]
                {
                    Manifest.Permission.WriteExternalStorage,
                    Manifest.Permission.RecordAudio
                }, REQUEST_PERMISSION_CODE);
            }
            else
            {
                isGrantedPermission = false;
            }


            strtRecordButton.Enabled = true;
            stpRecordButton.Enabled  = false;

            // Event
            strtRecordButton.Click += delegate
            {
                RecordAudio();
            };

            stpRecordButton.Click += delegate
            {
                StopRecord();
            };

            void RecordAudio()
            {
                if (isGrantedPermission)
                {
                    pathSave = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString() + "/" + new
                               Guid().ToString() + "_audio.3gp";

                    SetupMediaRecorder();

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

                        strtRecordButton.Enabled = false;
                        stpRecordButton.Enabled  = true;
                        Toast.MakeText(this, "Recording...", ToastLength.Short).Show();
                    }
                    catch (Exception Ex)
                    {
                        Log.Debug("DEBUG", Ex.Message);
                    }
                }

                stpRecordButton.Enabled = true;
            }

            void StopRecord()
            {
                mediaRecorder.Stop();
                strtRecordButton.Enabled = true;
                stpRecordButton.Enabled  = false;
                Toast.MakeText(this, "Stop Recording...", ToastLength.Short).Show();
            }

            void SetupMediaRecorder()
            {
                mediaRecorder = new MediaRecorder();
                mediaRecorder.SetAudioSource(AudioSource.Mic);
                mediaRecorder.SetOutputFormat(OutputFormat.ThreeGpp);
                mediaRecorder.SetAudioEncoder(AudioEncoder.AmrNb);
                mediaRecorder.SetOutputFile(pathSave);
            }

            //countButton = FindViewById<Button>(Resource.Id.countButton);
            //countText = FindViewById<TextView>(Resource.Id.countText);

            //countButton.Click += (sender, e) => { countText.Text = (++count).ToString(); };

            bckButton1.Click += (sender, e) =>
            {
                Intent nextActivivty = new Intent(this, typeof(SecondActivity));
                this.StartActivity(nextActivivty);
                this.Finish();
            };
        }
コード例 #30
0
ファイル: Video.cs プロジェクト: ArtemRim/HiddenCamera
 public void SetRecorderPreview()
 {
     recorder.SetPreviewDisplay(SufaceHolder.Surface);
     //.recorder.SetPreviewDisplay(null);
     recorder.Prepare();
 }