Saturday, 24 August 2013

How do I thread AudioRecorder?

How do I thread AudioRecorder?

I am following a tutorial on how to record WAV files on Android, source
files here:
https://github.com/roman10/roman10-android-tutorial/tree/master/AndroidWaveRecorder/src/roman10/tutorial/androidwaverecorder.
The issue with the code is that it isn't multi-threaded - therefore once
start() is called the UI thread is blocked, which isn't good. Although I
understand the concepts of threading I am lacking the logic to get this
code threaded, I have tried starting a new Thread() in the start() method
and onPeriodicNotification(AudioRecord recorder) method, as seen:
public void start() {
Thread recordThread = new Thread(new Runnable() {
public void run() {
if (state == State.READY) {
payloadSize = 0;
audioRecorder.startRecording();
state = State.RECORDING;
while (!cancelled){
audioRecorder.read(buffer, 0, buffer.length);
}
stop();
} else {
Log.e(WavAudioRecorder.class.getName(), "start() called on
illegal state");
state = State.ERROR;
}
}
});
recordThread.start();
}
private AudioRecord.OnRecordPositionUpdateListener updateListener = new
AudioRecord.OnRecordPositionUpdateListener() {
// periodic updates on the progress of the record head
public void onPeriodicNotification(AudioRecord recorder) {
Thread thread = new Thread(new Runnable() {
public void run() {
if (State.STOPPED == state) {
Log.d(WavAudioRecorder.this.getClass().getName(),
"recorder stopped");
return;
}
int numOfBytes = audioRecorder.read(buffer, 0,
buffer.length); // read audio data to buffer
Log.d(WavAudioRecorder.this.getClass().getName(), state +
":" + numOfBytes);
try {
randomAccessWriter.write(buffer); // write
audio data to file
payloadSize += buffer.length;
} catch (IOException e) {
Log.e(WavAudioRecorder.class.getName(), "Error
occurred in updateListener, recording is
aborted");
e.printStackTrace();
}
}
});
thread.start();
}
// reached a notification marker set by
setNotificationMarkerPosition(int)
public void onMarkerReached(AudioRecord recorder) {
}
};
Yet the above code still blocks the UI thread, does anyone have an idea on
how to get the code threaded?

No comments:

Post a Comment