title: Playing back sound coming from microphone in real-time
body: <p>I've been trying to get my application recording the sound coming from the microphone and playing it back in (approximately) real-time, however without success.</p>
  
  <p>I'm using AudioRecord and AudioTrack classes for record and playback, respectively. I've tried different approaches, I've tried to record the incoming sound and write it to a file and it worked fine. I've also tried to playback sound from that file AFTER with AudioTrack and it worked fine too. The problem is when I try to play the sound in real-time, instead of reading a file after it's written.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>//variables
  private int audioSource = MediaRecorder.AudioSource.MIC;
  private int samplingRate = 44100; /* in Hz*/
  private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
  private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
  private int bufferSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, audioFormat);
  private int sampleNumBits = 16;
  private int numChannels = 1;
  
  // …
  
  AudioRecord recorder = new AudioRecord(audioSource, samplingRate, channelConfig, audioFormat, bufferSize);
                  recorder.startRecording();
                  isRecording = true;
  
  AudioTrack audioPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                          AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
  
  if(audioPlayer.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)
      audioPlayer.play();
  
  //capture data and record to file
  int readBytes=0, writtenBytes=0;
  do{
     readBytes = recorder.read(data, 0, bufferSize);
  
     if(AudioRecord.ERROR_INVALID_OPERATION != readBytes){
        writtenBytes += audioPlayer.write(data, 0, readBytes);
     }
  }
  while(isRecording);
  </code></pre>
  
  <p>It is thrown a java.lang.IllegalStateException with the reason being caused by "play() called on a uninitialized AudioTrack".</p>
  
  <p>However, if I change the AudioTrack initialization for example to use sampling rate 8000Hz and sample format 8 bits (instead of 16), it doesn't throw the exception anymore and the application runs, although it produces horrible noise.</p>
  
  <p>When I play AudioTrack from a file, there is no problem with the initialization of the AudioTrack, I tried 44100 and 16 bits and it worked properly, producing the correct sound.</p>
  
  <p>Any help ?</p>