有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中字节数组到短数组再返回

我在获取存储在字节数组中的音频数据时遇到了一些问题,将其转换为一个大端短数组,对其进行编码,然后将其更改回字节数组。这是我的。原始音频数据存储在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++;
    }

我已经做了我能想到的一切来实现这一点,但最近的一次是让它每隔一次进行编码/解码,我不知道为什么。谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    我还建议你试试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);
    
  2. # 2 楼答案

    你的代码做的是小endian短裤,不是大的。您已经交换了MSB和LSB的索引

    由于您使用的是big-endian shorts,因此可以在另一端使用围绕ByteArrayInputStream(以及DataOutputStream/ByteArrayOutputStream)的DataInputStream,而不是自己解码

    如果你让其他每一次解码都能正常工作,我猜你的字节数是奇数,或者在其他地方出现了一个off-by-one错误,这会导致你的错误在每一次解码时被修复

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