package zouxe.streamclient;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import java.nio.ByteBuffer;

class AudioRecorder {
    private AudioRecord recorder = null;
    private Boolean isRecording = false;
    private Thread recordingThread = null;
    private float[] audioData = null;
    private int index = 0;
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private static final int BufferElements2Rec = 1024;

    public void record() {
        int bytesPerElement = 2;
        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * bytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                saveAudioData();
            }
        });
        recordingThread.start();
    }

    public void stopRecord() {
        isRecording = false;
        recorder.stop();
        recorder.release();
        recorder = null;
        recordingThread = null;
        index = 0;
    }

    private void saveAudioData() {
        while (isRecording) {
            if(audioData == null)
                audioData = new float[2048];
            if(index<1024) {
                byte[] data = new byte[BufferElements2Rec];
                recorder.read(data, 0, BufferElements2Rec);
                for(int i = 0; i < data.length; i+=4)
                    audioData[index++] = ByteBuffer.wrap(data,i,4).getFloat();
            }
        }
    }
}

@@ -154,16 +154,67 @@
 eBuffer;
+%0Aimport java.util.ArrayList;%0Aimport java.util.List;
 %0A%0Aclass 
@@ -370,15 +370,19 @@
 ate 
-f
+List%3CF
 loat
-%5B%5D
+%3E
  aud
@@ -400,35 +400,8 @@
 ll;%0A
-    private int index = 0;%0A
     
@@ -1175,24 +1175,141 @@
 ad.start();%0A
+        if(audioData == null)%0A            audioData = new ArrayList%3C%3E();%0A        else%0A            audioData.clear();%0A
     %7D%0A%0A    p
@@ -1477,27 +1477,8 @@
 ll;%0A
-        index = 0;%0A
     
@@ -1549,120 +1549,8 @@
 ) %7B%0A
-            if(audioData == null)%0A                audioData = new float%5B2048%5D;%0A            if(index%3C1024) %7B%0A    
     
@@ -1601,20 +1601,16 @@
 s2Rec%5D;%0A
-    
         
@@ -1669,20 +1669,16 @@
         
-    
 for(int 
@@ -1715,36 +1715,32 @@
                 
-    
 audioData%5Bindex+
@@ -1736,20 +1736,13 @@
 Data
-%5Bindex++%5D = 
+.add(
 Byte
@@ -1773,31 +1773,18 @@
 tFloat()
+)
 ;
-%0A            %7D
 %0A       

save audio data in arraylist instead of simple array