Monday, April 28, 2014

Adjust volume of 16-bits audio buffer

Recently, I found that it is so hard to adjust volume of the audio buffer (yeah... I am new on audio).

In this post, I learned how to adjust volume of 16-bits audio buffer easily.

Here is the code:

private byte[] adjustVolume(byte[] audioSamples, double volume)
    byte[] array = new byte[audioSamples.length];
    for (int i = 0; i < array.length; i+=2) {
        // convert byte pair to short
        short audioSample = (short) ((short) ((audioSamples[i+1] & 0xff) << 8) | (audioSamples[i] & 0xff));

        audioSample = (short) (audioSample * volume);

        // convert back
        array[i] = (byte) audioSample;
        array[i+1] = (byte) (audioSample >> 8);

    return array;

You can see that the code below is storing audiobuffer using "byte" datatype which is 8-bits datatype. Since our audio buffer is 16-buts datatype, you need to convert it into 16-bits datatype (I used "short") by using shift method (you can find another method to do this). And then, you can do what you want using this audio sample. Finally, you need to convert it back from 16-bits (short) audio sample into 8-bits (byte) audio buffer.

Please note that the manipulation is using one audio sample (in here, it is 16-bits audio sample).


No comments:

Post a Comment