title: Android program that Streams MIC directly to Speaker of Phone
body: <p>I am writing a Android program that Streams MIC directly to Speaker of Phone.The code works but UI hangs and app hangs.But Still audio transfer is working even if the app hangs.Where is the error..?</p>
  
  <pre><code> RecordBufferSize=AudioRecord.getMinBufferSize(sampleRateInHz,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
      TrackBufferSize= AudioTrack.getMinBufferSize(sampleRateInHz,AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT);
  
      am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      Record record = new Record();
      record.run();
  
  }
  public class Record extends Thread
  {
  
      final short[] buffer = new short[RecordBufferSize];
      short[] readBuffer = new short[TrackBufferSize];
  
      public void run() {
          isRecording = true;
          android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
          AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRateInHz,AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,RecordBufferSize);
          AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRateInHz,AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, TrackBufferSize, AudioTrack.MODE_STREAM);
          //am.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
          atrack.setPlaybackRate(sampleRateInHz);
          byte[] buffer = new byte[RecordBufferSize];
          arec.startRecording();
          atrack.play();
          while(isRecording) {
              AudioLenght=arec.read(buffer, 0, RecordBufferSize);
              atrack.write(buffer, 0, AudioLenght);
          }
          arec.stop();
          atrack.stop();
          isRecording = false;
      }
  }
  </code></pre>
  
  <p>This is my code.</p>