Beispiel #1
0
        public Task <bool> BeginCaptureAudio()
        {
            if (_recorder != null)
            {
                _recorder.Release();
                _recorder.Dispose();
            }

            _audioCaptureStream = new MemoryStream();
            MediaHelper.WriteWavHeader(_audioCaptureStream, MediaHelper.DefaultAudioSamplingRate);

            _recorder = new AudioRecord(AudioSource.Mic, MediaHelper.DefaultAudioSamplingRate, ChannelIn.Mono, Encoding.Pcm16bit, _audioBuffer.Length);

            if (_recorder.State != State.Initialized)
            {
                _recorder = null;
                return(Task.FromResult(false));
            }

            _recorder.StartRecording();
            _trimAudioZeros = true;

            ReadAudioBufferAsync();
            return(Task.FromResult(true));
        }
 public void Stop()
 {
     if (_isRecording == true)
     {
         _isRecording = false;
         audRecorder.Stop();
         audioDataBytes = File.ReadAllBytes(wavPath);
         audRecorder.Release();
     }
 }
Beispiel #3
0
        public void Clear()
        {
            recorder?.Stop();
            recorder?.Release();
            recorder?.Dispose();
            recorder = null;

            audioTrack?.Stop();
            audioTrack?.Release();
            audioTrack?.Dispose();
            audioTrack = null;
        }
Beispiel #4
0
        async Task ReadAudioAsync()
        {
            using (var fileStream = new FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                while (true)
                {
                    if (endRecording)
                    {
                        endRecording = false;
                        break;
                    }
                    try
                    {
                        // Keep reading the buffer while there is audio input.
                        int numBytes = await audioRecord.ReadAsync(audioBuffer, 0, audioBuffer.Length);

                        await fileStream.WriteAsync(audioBuffer, 0, numBytes);

                        // Do something with the audio input.
                    }
                    catch (Exception ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                        break;
                    }
                }
                fileStream.Close();
            }
            audioRecord.Stop();
            audioRecord.Release();
            isRecording = false;

            RaiseRecordingStateChangedEvent();
        }
Beispiel #5
0
        /// <summary>
        /// Stops the audio stream.
        /// </summary>
        public Task Stop()
        {
            if (Active)
            {
                audioSource.Stop();
                audioSource.Release();

                OnActiveChanged?.Invoke(this, false);
            }
            else             //just in case
            {
                audioSource.Release();
            }

            return(Task.FromResult(true));
        }
Beispiel #6
0
    void readLoop()
    {
        byte[] buffer = new byte[bufferSize];
        while (!stopRecording)
        {
            try
            {
                int num_bytes = audioRecorder.Read(buffer, 0, buffer.Length);

                byte[] data_to_send = new byte[num_bytes];
                Array.Copy(buffer, data_to_send, num_bytes);

                Task.Run(() =>
                {
                    OnSoundDataReceived(data_to_send);
                });
            }
            catch (Exception e)
            {
                Logging.error("Exception occured while recording audio stream: " + e);
                break;
            }
            Thread.Sleep(10);
        }
        audioRecorder.Stop();
        audioRecorder.Release();
        audioRecorder.Dispose();
        audioRecorder = null;
        running       = false;
    }
        public void Stop()
        {
            lock (stateLocker)
            {
                if (recorder != null)
                {
                    if (recorder.RecordingState == RecordState.Recording)
                    {
                        recorder.Stop();
                        recorder.Release();
                        recorder        = null;
                        recordingThread = null;
                    }
                }

                if (player != null)
                {
                    if (player.PlayState == PlayState.Playing)
                    {
                        player.Stop();
                        player.Release();
                        player = null;
                    }
                }

                OnMessage?.Invoke(this, "Stopped");
            }
        }
Beispiel #8
0
 public void AudioPlayRelease()
 {
     record.Stop();
     audioTrack.Stop();
     audioTrack.Release();
     record.Release();
 }
        /// <summary>
        /// Stop recorder
        /// </summary>
        public void StopRecording()
        {
            isRecording = false;
            try
            {
                if (audioRecord.State == State.Initialized)
                {
                    // Stop Audio Recorder
                    audioRecord.Stop();
                    audioRecord.Release();
                    audioRecord = null;
                    // Stop thread
                    audioThread.Abort();
                    delegateThreadStart = null;
                    audioThread         = null;
                }

                // Create file path for .wav file
                wavFile = Android.OS.Environment.ExternalStorageDirectory.Path + "/AudioRecorderFile.wav";
                ConvertRawFileToWavFile(rawFile, wavFile);
                // Delete temp file
                new Java.IO.File(rawFile).Delete();
            }
            catch (Exception e)
            {
                throw new System.ArgumentException(e.Message);
            }
        }
Beispiel #10
0
 public void Dispose()
 {
     Stop();
     _record.Release();
     _readSubject.OnCompleted();
     _readSubject.Dispose();
     _record.Dispose();
 }
Beispiel #11
0
        public void IniciarGrabacion()
        {
            var context      = Android.App.Application.Context;
            var audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            RECORDER_SAMPLERATE = Int32.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));

            if (recorder != null)
            {
                recorder.Release();
            }

            recorder = new AudioRecord(AudioSource.Mic, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
            recorder.StartRecording();
            isRecording = true;

            token = new CancellationTokenSource();
            Task.Run(() => WriteAudioDataToFile(), token.Token);
        }
Beispiel #12
0
 /**
  * need to call this when completely done with recording
  */
 public void done()
 {
     Log.Debug(TAG, "shut down recorder");
     if (recorder != null)
     {
         recorder.Stop();
         recorder.Release();
         recorder = null;
     }
 }
        public void StartRecording()
        {
            _recorder?.Release();

            _recorder = new AudioRecord(AudioSource.Mic, _deviceService.AudioSampleRate, _recorderChannels, _recorderAudioEncoding, _bufferSize);
            _recorder.StartRecording();
            _isRecording = true;

            Task.Run(() => WriteAudioDataToFile());
        }
Beispiel #14
0
        protected override void OnPause()
        {
            base.OnPause();

            player?.Release();
            player?.Dispose();
            player = null;
            audRecorder?.Stop();
            audRecorder?.Release();
            audRecorder = null;
        }
Beispiel #15
0
        public void StartRecording()
        {
            var context      = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;
            var audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            RECORDER_SAMPLERATE = Int32.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));

            if (recorder != null)
            {
                recorder.Release();
            }

            bufferSize = AudioRecord.GetMinBufferSize(RECORDER_SAMPLERATE, ChannelIn.Mono, Encoding.Pcm16bit);
            recorder   = new AudioRecord(AudioSource.Mic, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
            recorder.StartRecording();
            isRecording = true;

            token = new CancellationTokenSource();
            Task.Run(() => WriteAudioDataToFile(), token.Token);
        }
Beispiel #16
0
        /// <summary>
        /// To pause service when app goes to background
        /// </summary>
        public override void Pause()
        {
            Log.Debug(TAG, "Pause");
            StopListening();

            if (audioRecord != null)
            {
                audioRecord.Release();
                audioRecord = null;
            }
        }
Beispiel #17
0
 private void KillAudioJack()
 {
     try
     {
         audioJack.Stop();
         audioJack.Release();
     }
     catch {
         //do nothing, this was anyhow just an attempt to release the audio jack in a clean way
     }
 }
Beispiel #18
0
 public void StopRecording()
 {
     if (recorder != null)
     {
         recorder.Stop();
         isRecording = false;
         token.Cancel();
         recorder.Release();
         recorder = null;
     }
     CopyWaveFile(GetTempFilename(), GetFilename());
 }
        public void StartRecording()
        {
            var context      = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;
            var audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            recorderSampleRate = Int32.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));

            if (recorder != null)
            {
                recorder.Release();
            }

            bufferSize = AudioRecord.GetMinBufferSize(recorderSampleRate, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit);
            recorder   = new AudioRecord(AudioSource.Mic, recorderSampleRate, ChannelIn.Stereo,
                                         Android.Media.Encoding.Pcm16bit, bufferSize);
            recorder.StartRecording();
            isRecording = true;

            token = new CancellationTokenSource();
            Task.Run(() => WriteAudioDataToFile(), token.Token);
        }
Beispiel #20
0
        public void StopRecording()
        {
            if (_recorder == null)
            {
                return;
            }

            _isRecording = false;

            _recorder.Stop();
            _recorder.Release();
            _recorder = null;
        }
Beispiel #21
0
        private async Task RecordAudio(List <byte[]> audioTracks, MemoryStream memoryStream)
        {
            if (memoryStream == null)
            {
                memoryStream = new MemoryStream();
            }

            while (true)
            {
                if (endRecording)
                {
                    endRecording = false;
                    break;
                }

                try
                {
                    // Keep reading the buffer while there is audio input.

                    await audioRecorder.ReadAsync(audioBuffer, 0, audioBuffer.Length);

                    // Write out the audio file.
                    await memoryStream.WriteAsync(audioBuffer, 0, audioBuffer.Length);

                    await Console.Out.WriteLineAsync("RECORDING SOUND. Memory stream size:" + memoryStream.Length);
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.Message);
                    break;
                }
            }

            await Console.Out.WriteLineAsync("We successfully stopped recording.");

            audioRecorder.Stop();
            audioRecorder.Release();

            var mainTextView = activity.FindViewById <TextView>(mainTextViewId);

            if (memoryStream.Length > 0)
            {
                audioTracks.Add(memoryStream.ToArray());
                mainTextView.Text = "Numbers of Tracks:" + audioTracks.Count;
            }

            isRecording = false;

            RaiseRecordingStateChangedEvent();
        }
        public void Stop()
        {
            if (_isRecording && _recorder == null)
            {
                _tcs.TrySetResult(new AudioRecordResult($"Not recording"));
            }

            _timeoutToken?.Cancel();
            _isRecording = false;

            if (_recorder.State == State.Initialized)
            {
                _recorder.Stop();
            }

            _recorder.Release();

            // Android audio is raw stream content, so add WAV header
            var wavstream = new MemoryStream();

            WriteWaveFileHeader(wavstream, _ms.Length, _options.SampleRate, 1);

            _ms.Seek(0, SeekOrigin.Begin);
            _ms.CopyTo(wavstream);
            _ms.Close();
            _ms.Dispose();
            _ms = null;

            if (_options.StreamFormat == AudioRecordOptions.Format.Wave)
            {
                _tcs.TrySetResult(new AudioRecordResult(wavstream.ToArray()));
            }
            else if (_options.StreamFormat == AudioRecordOptions.Format.Flac)
            {
                // encode audio into flac
                using (var ms = new MemoryStream())
                {
                    using (var what = new WaveOverFlacStream(ms, WaveOverFlacStreamMode.Encode, true))
                    {
                        wavstream.Seek(0, SeekOrigin.Begin);
                        wavstream.CopyTo(what);
                    }

                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    _tcs.TrySetResult(new AudioRecordResult(ms.ToArray()));
                }
            }
        }
        public void StopRecording()
        {
            WvlLogger.Log(LogType.TraceAll, "StopRecording()");

            if (null != audioRecord)
            {
                isRecording = false;
                if (audioRecord.State == State.Initialized)
                {
                    audioRecord.Stop();
                }
                audioRecord.Release();

                audioRecord     = null;
                recordingThread = null;
            }

            /*
             * if (null != audioRecordCharts)
             * {
             *  if (audioRecordCharts.State == State.Initialized)
             *  {
             *      audioRecordCharts.Stop();
             *
             *      // Write file after recording
             *      isWriting = true;
             *      WriteAudioDataToFileAfterRecording();
             *  }
             *  audioRecordCharts.Release();
             *
             *  audioRecordCharts = null;
             *  chartsThread = null;
             *
             *  samplesUpdatedThread = null;
             * }
             */

            /*
             * if (audioRecordCharts.State == State.Initialized)
             * {
             *  audioRecordCharts.Stop();
             *  WriteAudioDataToFileAfterRecording();
             * }
             * audioRecordCharts.Release();
             */

            CopyWaveFile(GetTempFilename(), GetFilename());
            //DeleteTempFile();
        }
        public string StopRecording()
        {
            if (_recorder != null)
            {
                _isRecording = false;
                _recorder.Stop();
                _recorder.Release();
                _recorder = null;
            }

            var file = GetFilename(Guid.NewGuid().ToString());

            CopyWaveFile(GetTempFilename(), file);
            return(file);
        }
Beispiel #25
0
 /** Stops the stream. */
 public void stop()
 {
     if (mStreaming)
     {
         if (mMode == MODE_MEDIACODEC_API)
         {
             Log.d(TAG, "Interrupting threads...");
             mThread.Interrupt();
             mAudioRecord.Stop();
             mAudioRecord.Release();
             mAudioRecord = null;
         }
         base.stop();
     }
 }
        public void StartRecording()
        {
            var context      = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;
            var audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            _recorderSamplerate = int.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));

            _recorder?.Release();

            _bufferSize = AudioRecord.GetMinBufferSize(_recorderSamplerate, ChannelIn.Stereo, Encoding.Pcm16bit) * 3;
            _recorder   = new AudioRecord(AudioSource.Mic, _recorderSamplerate, RecorderChannels, RecorderAudioEncoding, _bufferSize);
            _recorder.StartRecording();
            _isRecording = true;

            _token = new CancellationTokenSource();
            Task.Run(() => WriteAudioDataToFile(), _token.Token);
        }
Beispiel #27
0
        private void ReadThread()
        {
            _record.StartRecording();
            while (_isrecording)
            {
                var size = _record.Read(_tmpBuffer, 0, _tmpBuffer.Length);

                for (var i = 0; i < _tmpBuffer.Length; i++)
                {
                    _buffer[i] = _tmpBuffer[i] / 32767.0f;//(_tmpBuffer[i] > 100 || _tmpBuffer[i]<-100) ? _tmpBuffer[i] / 32767.0f : 0f;
                }
                _callback?.Invoke(_buffer);
            }
            _record.Stop();
            _record.Release();
            _record.Dispose();
        }
Beispiel #28
0
        public SpeechRecognizer(Config config)
        {
            _decoder   = new Decoder(config);
            sampleRate = (int)_decoder.GetConfig().GetFloat("-samprate");
            bufferSize = Java.Lang.Math.Round(sampleRate * BUFFER_SIZE_SECONDS);
            _recorder  = new AudioRecord(
                AudioSource.VoiceRecognition, sampleRate,
                ChannelIn.Mono,
                Encoding.Pcm16bit, bufferSize * 2);

            if (_recorder.State == State.Uninitialized)
            {
                _recorder.Release();
                throw new IOException(
                          "Failed to initialize recorder. Microphone might be already in use.");
            }
        }
Beispiel #29
0
    private void cleanUp()
    {
        running = false;

        if (audioRecorder != null)
        {
            try
            {
                audioRecorder.Stop();
                audioRecorder.Release();
            }catch (Exception)
            {
            }
            audioRecorder.Dispose();
            audioRecorder = null;
        }

        if (audioEncoder != null)
        {
            try
            {
                audioEncoder.Stop();
                audioEncoder.Release();
            }
            catch (Exception)
            {
            }
            audioEncoder.Dispose();
            audioEncoder = null;
        }

        buffer     = null;
        bufferSize = 0;
        lock (outputBuffers)
        {
            outputBuffers.Clear();
        }
        lock (availableBuffers)
        {
            availableBuffers.Clear();
        }
    }
Beispiel #30
0
 public override void OnDestroy()
 {
     base.OnDestroy();
     if (tokenSource != null)
     {
         try
         {
             tokenSource.Cancel();
             task.Wait();
         }
         catch (AggregateException)
         {
             record.Stop();
             record.Release();
             ws.Close();
             task.Dispose();
             Console.WriteLine("Task Cancelled.");
         }
     }
 }