Search code examples
androidaudiotrack

AudioTrack release


I am wondering if I need to call release on an audio track?

For example, in my following code I instantiate a AudioTrack instance in a method, and do not call release on it (because that stops play).

What are the repercussions of this?

public void playTone()
{
    float[] output = createTone();

    AudioTrack track = new AudioTrack(AudioManager.STREAM_RING, 44100,
            AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            (output.length*4),
            AudioTrack.MODE_STATIC);

    short[] result =  new short[output.length];

    for(int i = 0; i < output.length; i++)
        result[i] = (short) ((output[i])*32768);

    track.write(result, 0, output.length);
    track.play();
}

Solution

  • If you don't call release(), you will leak the native memory behind the Java AudioTrack object. AudioTrack is not all entirely Java, so the call is required to let the native code to free its own memory because it won't be garbage collected.

    You should always call release() when done to avoid problems related to consuming too much memory in your app.