Search code examples
androidexceptionmemoryoutaudiorecord

AudioRecord Out of Memory Exception


I created an object that continuously reads the input from the mic but I'm having some troubles with it. I need to be able to pause and start it, so I've implemented the methods, but the problem is that, on an older phone (Galaxy Y) it works very well the first time I start it, but after I pause it and start it again it quickly crashes due to OutOfMemoryException.

@Override
public void run() {
    while (mIsRunning) {
        synchronized (mThread) {
            while (mIsPaused) {
                try {
                    mThread.wait();
                } catch (InterruptedException e) {
                }
            }
        }
        double sum = 0;
        int readSize = mRecorder.read(mBuffer, 0, mBuffer.length);

        if (readSize > 0) {
            short[] samples = new short[readSize];
            for (int i = 0; i < readSize; i++) {
                sum += mBuffer[i] * mBuffer[i];
                samples[i] = mBuffer[i];
            }

            final int amplitude = (int) Math.sqrt((sum / readSize));

            Message message = new Message();
            message.arg1 = amplitude;
            message.arg2 = readSize;
            message.obj = samples;
            message.what = 0;

            if (mHandler != null)
                mHandler.sendMessage(message);

        }

    }

}

public void start() {
    if (!mIsRunning) {
        mIsRunning = true;
        mThread.start();
    } else synchronized (mThread) {
        mIsPaused = false;
        mThread.notifyAll();
    }

    mRecorder.startRecording();

}

public void pause() {
    synchronized (mThread) {
        mIsPaused = true;
    }

    mRecorder.stop();

}

So, the first time all works well, but after I call stop() on the AudioRecord and start reading the input again I quickly run out of memory. Any ideas on how to fix this? I was thinking of just not stopping the recording and just not sending the data through the handler but I don't know. Thanks.


Solution

  • The solution was destroying (and releasing) the AudioRecord object on every pause and just recreating it on each start.