Hi all,
Was wondering if anyone could help me on background threading on Android.
I have a piece of code that records from the mic of the device and then plays back what it records through the ear piece(on 1.5).
I am trying to run it in a thread but have been unsuccessful in getting it to run as a background thread.
Currently it runs and locks up the activity so that all thats happening is the thread is running and the UI is locked up or appears to be hanging.
Here is the lastest way I tried to do it:
public class LoopProg extends Activity {
boolean isRecording; //currently not used
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AudioManager audio_service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio_service.setSpeakerphoneOn(false);
audio_service.setMode(AudioManager.MODE_IN_CALL);
audio_service.setRouting(AudioManager.MODE_NORMAL,
AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
Record record = new Record();
record.run();
}
public class Record extends Thread
{
static final int bufferSize = 200000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
public void run() {
isRecording = true;
android.os.Process.setThreadPriority
(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
int buffersize = AudioRecord.getMinBufferSize(11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
buffersize);
AudioTrack atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
buffersize,
AudioTrack.MODE_STREAM);
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
atrack.setPlaybackRate(11025);
byte[] buffer = new byte[buffersize];
arec.startRecording();
atrack.play();
while(isRecording) {
arec.read(buffer, 0, buffersize);
atrack.write(buffer, 0, buffer.length);
}
arec.stop();
atrack.stop();
isRecording = false;
}
}
}
I was wondering could anyone guide me on how to turn this into a background thread? Or point me to some tutorial that may be relevant that I may have missed?
Thanks in advance