I am trying to use an AudioRecord object in android to record audio data into a byte array and simultaneously perform some analysis on the recorded data. But I am unsure how to do it. If I use the byte array directly the application crashes. I need a byte array as an input for the analysing thread I am relatively new to android development and I would appreciate any help on this topic. Thanks
byte[] data;
public void Record()throws IOException{
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
isRecording = true;
boolean flag = true;
data = new byte[bufferSize];
while(isRecording){
try {
int result = recorder.read(data, 0, bufferSize);
if(flag){
Thread analyseThread = new Thread(new Runnable() {
@Override
public void run() {
theAnalysingFunction();
}
},"AudioRecorder Thread");
analyseThread.start();
flag=false;
}
if (AudioRecord.ERROR_INVALID_OPERATION !=result ) {
} else if (result == AudioRecord.ERROR_INVALID_OPERATION) {
Log.e("Recording", "Invalid operation error");
break;
} else if (result == AudioRecord.ERROR_BAD_VALUE) {
Log.e("Recording", "Bad value error");
break;
} else if (result == AudioRecord.ERROR) {
Log.e("Recording", "Unknown error");
break;
}
} catch (Exception e) {
Log.i("Error", "AudioRecord error");
}
}
}
public void theAnalysingFunction(){
//
//Analyse the byte array named data
//
}
This is multithreading. You try to analyze a buffer. While another thread changes it simultaneously.
About your crash, if U use a byte buffer, make sure U use ENCODING_PCM_8BIT for encoding.