3

I'm working with some code that calls the AudioRecord constructor:

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

This code would seem to make sense if AudioRecord goes off in another thread and takes time to initialize. I'm not sure of this is the case though, and if it isn't it would seem a lot better to have the code just check and return an exception, lest an infinite loop is started at some point when initialization does actually fail (although I could just limit the number of checks to something finite).

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

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

2 回答 2

3

看源码就很清楚了:

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;
    }

所以你不必等待它的状态转换。您只需要在调用构造函数一次后检查状态。如果 native_setup 有任何问题,状态将为 STATE_UNINITIALIZED。

于 2013-02-26T07:56:44.633 回答
1

我会说抛出一个异常。我有一个使用 AudioRecord 的应用程序,下载量 > 1000000,它不必等待 AudioRecord 状态。(并且您至少需要一个 Thread.sleep() 在您的 while 循环中,以确保您在等待 AudioRecord 时不会消耗 100% 的 CPU,如果您确实需要这样做的话。)

于 2013-02-26T07:33:11.430 回答