Java – Is it useful to put AudioRecord.getState() in a loop?

Is it useful to put AudioRecord.getState() in a loop?… here is a solution to the problem.

Is it useful to put AudioRecord.getState() in a loop?

I’m using some code constructor that calls AudioRecord:

AudioRecord listener = new AudioRecord(list of parameters);
do {} while (listener.getState() != AudioRecord.STATE_INITIALIZED);

This code seems to make sense if the AudioRecord is closed in another thread and takes time to initialize. I’m not sure if that’s the case, and if not, it would seem much better to have the code just check and return an exception, so as not to start an infinite loop at some point when initialization does fail (although I could limit the number of checks to a limited range).

Should I leave the code as it is or replace the second line with something like this?

if(listener.getState() != AudioRecord.STATE_INITIALIZED) {
    throw new Exception("AudioRecord failed to initialize");
}

Solution

It’s clear by looking at the source code:

public AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, 
            int bufferSizeInBytes)
    throws IllegalArgumentException {   
        mState = STATE_UNINITIALIZED;
        mRecordingState = RECORDSTATE_STOPPED;

... //parameter checks

 native initialization
        update native initialization when information about hardware init failure
        due to capture device already open is available.
        int initResult = native_setup( new WeakReference<AudioRecord>(this), 
                mRecordSource, mSampleRate, mChannels, mAudioFormat, mNativeBufferSizeInBytes);
        if (initResult != SUCCESS) {
            loge("Error code "+initResult+" when initializing native AudioRecord object.");
            return;  with mState == STATE_UNINITIALIZED
        }

mState = STATE_INITIALIZED;
    }

So you don’t have to wait for its state to transition. You only need to check the status after calling the constructor once. If there are any errors for native_setup, the status will be STATE_UNINITIALIZED.

Related Problems and Solutions