Buddy
Buddy

Reputation: 2114

Update UI Immediately for Real-Time Processing

I am developing a real-time audio processing software which should update the UI in at least 100ms from the worker thread. However, this appears harder to achieve than it looks.

I am calling runOnUiThread(uiUpdaterRunnable) from the worker thread but the delay of execution of uiUpdaterRunnable is variable and generally more than 300ms.

I tried to Use AsyncTask with publishProgress but it also gave me similar results.

How can i update UI from the worker thread to get at least 10FPS ?

Here is the runnable of my worker thread :

new Runnable() {
public void run() {
 try {



            int sampleRate = 44100;
            int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
            int channelConfig = MediaRecorder.AudioSource.MIC;
            int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
            audioRecorder = new AudioRecord(channelConfig, sampleRate, AudioFormat.CHANNEL_IN_MONO, audioFormat, bufferSize);
            if (bufferSize == AudioRecord.ERROR_BAD_VALUE)
                Log.i("AudioRecord", "AudioRecord Bad Buffer Size");
            if (audioRecorder.getState() == AudioRecord.STATE_INITIALIZED)
                Log.i("AudioRecord", "AudioRecord Initialized Successfully");

            audioRecorder.startRecording();
        while (recording) {
            startTime = System.currentTimeMillis();
            short[] buffer = new short[bufferSize];
            audioRecorder.read(buffer, 0, bufferSize);

            double[] bufferDouble = shortToDoubleArray(buffer);

            final DataPoint[] resultArray = getFFTResult(bufferDouble);


             //This is where I update UI
            runOnUiThread(new Runnable() {
                 public void run() {
                updateGraph(resultArray);
                }
            });

        }
        releaseAudioResources();
    } catch (Exception e) {
        if (e.getMessage() == null)
            e.printStackTrace();
        else
            Log.e("Exception", e.getMessage());
        releaseAudioResources();
    }
}

Upvotes: 0

Views: 459

Answers (1)

Cyph3rCod3r
Cyph3rCod3r

Reputation: 2088

}
....
// write this outside your code block
 Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        updateGraph(resultArray);
    }
};
// to call it inside runnable
mHandler.sendEmptyMessage(0);

Upvotes: 1

Related Questions