Audio file - Manipulate volume given byte frames -

2019-09-01 09:44发布

I have a .au audio file that I am trying to copy to another audio file, and I want the copied audio file to have half the volume. I have written the following code and it produces the following audio file:

for (int i = 24; i < bytes.length; i++) {
    // bytes is a byte[] array containing every byte in the .au file
    if (i % 2 == 0) {
        short byteFrame = (short) (((bytes[i - 0]&0xFF) << 8) | ((bytes[i - 1]&0xFF)));
        byteFrame >>= 1;
        bytes[i - 0] = (byte) (byteFrame);
        bytes[i - 1] = (byte) (byteFrame >>> 8);
    }
}

The data I get from that code is this: enter image description here

The following code is the same as above, only 'bytes[i - 0]' and 'bytes[i - 1]' have switched places. When I do that, the information in the channels gets swapped to the other channel.

for (int i = 24; i < bytes.length; i++) {
    // bytes is a byte[] array containing every byte in the .au file
    if (i % 2 == 0) {
        short byteFrame = (short) (((bytes[i - 0]&0xFF) << 8) | ((bytes[i - 1]&0xFF)));
        byteFrame *= 0.5;
        bytes[i - 1] = (byte) (byteFrame);
        bytes[i - 0] = (byte) (byteFrame >>> 8);
    }
}

The data I get from that code is this (Information in the channels has been swapped): enter image description here

I need to reduce the volume in both channels by half. Below is the wikipedia page on the au file format. Any ideas on how to get it to work properly in reducing the volume? This file is encoding 1 (8-bit G.711 mu-law), 2 channels, 2 bytes per frame, and sample rate of 48000. (It works properly on Encoding 3 but not encoding 1.) Thanks in advance for any help offered.

http://en.wikipedia.org/wiki/Au_file_format

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-01 10:13

Use a ByteBuffer. It appears that you use 16 bit quantities in little endian order, and that you want to right shift them by 1.

Therefore:

final ByteBuffer orig = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
    .asReadOnlyBuffer();

final ByteBuffer transformed = ByteBuffer.wrap(bytes.length)
    .order(ByteOrder.LITTLE_ENDIAN);

while (orig.hasRemaining())
    transformed.putShort(orig.getShort() >>> 1);

return transformed.array();

Note that the >>> is necessary; otherwise you carry the sign bit.

That is, trying to use >> 1 on:

1001 0111

will give:

1100 1011

ie, the sign bit (the most significant bit) is carried. This is why >>> exists in Java, which DOES NOT carry the sign bit, therefore using >>> 1 on the above will give:

0100 1011

As seems logical when doing bit shifting!

查看更多
登录 后发表回答