52

我在获取存储在字节数组中的音频数据,将其转换为大端短数组,对其进行编码,然后将其更改回字节数组时遇到了一些问题。这就是我所拥有的。原始音频数据存储在 audioBytes2 中。我使用相同的格式进行解码,但在 cos 函数上加减号。不幸的是,更改字节和短数据类型是不可协商的。

    short[] audioData = null;
    int nlengthInSamples = audioBytes2.length / 2;
    audioData = new short[nlengthInSamples];

    for (int i = 0; i < nlengthInSamples; i++) {
       short MSB = (short) audioBytes2[2*i+1];
       short LSB = (short) audioBytes2[2*i];
       audioData[i] = (short) (MSB << 8 | (255 & LSB));
    }

    int i = 0;
    while (i < audioData.length) {
        audioData[i] = (short)(audioData[i] + (short)5*Math.cos(2*Math.PI*i/(((Number)EncodeBox.getValue()).intValue())));
        i++;
    }

    short x = 0;
    i = 0;
    while (i < audioData.length) {
        x = audioData[i];
        audioBytes2[2*i+1] = (byte)(x >>> 0);
        audioBytes2[2*i] = (byte)(x >>> 8);
        i++;
    }

我已经做了我能想到的一切来完成这项工作,但我最接近的是让它在其他所有编码/解码中工作,我不知道为什么。谢谢你的帮助。

4

6 回答 6

103

我也建议你试试 ByteBuffer。

byte[] bytes = {};
short[] shorts = new short[bytes.length/2];
// to turn bytes to shorts as either big endian or little endian. 
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);

// to turn shorts back to bytes.
byte[] bytes2 = new byte[shortsA.length * 2];
ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shortsA);
于 2011-04-11T18:49:41.213 回答
12
public short bytesToShort(byte[] bytes) {
     return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
}
public byte[] shortToBytes(short value) {
    return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(value).array();
}
于 2013-08-08T06:30:04.520 回答
6

一些 ByteBuffers 怎么样?

byte[] payload = new byte[]{0x7F,0x1B,0x10,0x11};
ByteBuffer bb = ByteBuffer.wrap(payload).order(ByteOrder.BIG_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
while(sb.hasRemaining()){
  System.out.println(sb.get());
}
于 2011-04-11T18:48:11.497 回答
5
byte[2] bytes;

int r = bytes[1] & 0xFF;
r = (r << 8) | (bytes[0] & 0xFF);

short s = (short)r;
于 2015-06-27T10:59:46.157 回答
2

您的代码正在做 little-endian 短裤,不是很大。您已经交换了 MSB 和 LSB 的索引。

由于您使用的是 big-endian 短裤,因此您可以在另一端使用包裹在 ByteArrayInputStream(和 DataOutputStream/ByteArrayOutputStream)周围的 DataInputStream,而不是自己进行解码。

如果您使其他所有解码都正常工作,我猜您的字节数为奇数,或者其他地方出现了一个错误,这导致您的错误在其他所有通道中都得到修复。

最后,我将使用 i+=2 遍历数组并使用 MSB= arr[i] 和 LSB=arr[i+1] 而不是乘以 2,但这只是我。

于 2011-04-11T18:30:05.607 回答
-1

看起来您在读取字节和将它们写回之间交换字节顺序(不确定这是否是故意的)。

于 2011-04-11T18:34:23.857 回答