how to reverse AudioTrack play()

367 views Asked by At

I have buffer (array) full of audio data, filled with AudioRecord method. I want play this reversed. When I try to reverse the buffer I just get noise.

public void startWriteAndPlayProcess (){
    writeAudio();
    playAudio();
}

private void writeAudio(){
     audioTrack.write(reverseArray(audioBuffer), 0, bufferSize);
}

private void playAudio(){
    audioTrack.play();
}

private byte []  reverseArray ( byte array []){
    byte  [] array1 = new byte [array.length];
    for (int i=0; i<array1.length; i++){
        array1[i]= array[array1.length-1-i];
    }
    return array1;
 }

What You people can recomend?

1

There are 1 answers

1
jaket On BEST ANSWER

The underlying audio samples are actually an array of shorts (16-bit) or ints (24 or 32-bit). If you just reverse the raw byte array then you are putting the least significant byte on the top and this will make your signal sound like noise. To get it to work properly you need to first convert the byte array to an array of the proper type, reverse that, and then convert it back into a byte array.

private void writeAudio()
{
    short[] shortArray = toShortArray(audioBuffer);
    short[] reversedShortArray = reverseArray(shortArray);
    byte[] reversedByteArray = toByteArray(reversedShortArray);
    audioTrack.write(reversedByteArray, 0, bufferSize);
}

private short[] toShortArray(byte[] byteArray)
{
    short[] shortArray = new short[byteArray.length / 2];
    for (int i = 0 ; i < shortArray.length; i)
    {
         shortArray[i] = (short)((short)byteArray[i*2] | (short)(byteArray[i*2 + 1] << 8));
         // alternatively - depending on the endianess of the data:
         // shortArray[i] = (short)((short)byteArray[i*2] << 8 | (short)(byteArray[i*2 + 1]));
    }
    return shortArray;
}

Of course you'll have to change the type of reverseArray. I'll leave it up to you to figure out how to go back to bytes from the short array or to write the int versions of them if that's what you need.