将字节数组转换为双数组

Lea*_*o T 3 java arrays fft wav

我在Java中遇到了WAV文件的一些问题.

WAV格式:PCM_SIGNED 44100.0 Hz,24位,立体声,6字节/帧,小端.

  • 我将WAV数据提取到一个没有问题的字节数组.
  • 我正在尝试将字节数组转换为双数组,但有些双精度数字带有"NaN"值.

码:

ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
double[] doubles = new double[byteArray.length / 8];
for (int i = 0; i < doubles.length; i++) {
    doubles[i] = byteBuffer.getDouble(i * 8);
}
Run Code Online (Sandbox Code Playgroud)

16/24/32位,单声道/立体声的事实让我感到困惑.

我打算将double []传递给FFT算法并获得音频.

谢谢

小智 9

试试这个:

public static byte[] toByteArray(double[] doubleArray){
    int times = Double.SIZE / Byte.SIZE;
    byte[] bytes = new byte[doubleArray.length * times];
    for(int i=0;i<doubleArray.length;i++){
        ByteBuffer.wrap(bytes, i*times, times).putDouble(doubleArray[i]);
    }
    return bytes;
}

public static double[] toDoubleArray(byte[] byteArray){
    int times = Double.SIZE / Byte.SIZE;
    double[] doubles = new double[byteArray.length / times];
    for(int i=0;i<doubles.length;i++){
        doubles[i] = ByteBuffer.wrap(byteArray, i*times, times).getDouble();
    }
    return doubles;
}

public static byte[] toByteArray(int[] intArray){
    int times = Integer.SIZE / Byte.SIZE;
    byte[] bytes = new byte[intArray.length * times];
    for(int i=0;i<intArray.length;i++){
        ByteBuffer.wrap(bytes, i*times, times).putInt(intArray[i]);
    }
    return bytes;
}

public static int[] toIntArray(byte[] byteArray){
    int times = Integer.SIZE / Byte.SIZE;
    int[] ints = new int[byteArray.length / times];
    for(int i=0;i<ints.length;i++){
        ints[i] = ByteBuffer.wrap(byteArray, i*times, times).getInt();
    }
    return ints;
}
Run Code Online (Sandbox Code Playgroud)


MvG*_*MvG 4

您的 WAV 格式是 24 位,但 double 使用 64 位。所以你的wav中存储的数量不能是双倍的。每帧和通道都有一个 24 位有符号整数,相当于提到的 6 个字节。

你可以这样做:

private static double readDouble(ByteBuffer buf) {
  int v = (byteBuffer.get() & 0xff);
  v |= (byteBuffer.get() & 0xff) << 8;
  v |= byteBuffer.get() << 16;
  return (double)v;
}
Run Code Online (Sandbox Code Playgroud)

您将为左通道调用该方法一次,为右通道调用该方法一次。不确定顺序是否正确,但我想先离开。字节从最低有效位到最高有效位读取,如小端字节序所示。较低的两个字节被掩码,0xff以便将它们视为无符号。最高有效字节被视为有符号,因为它将包含有符号 24 位整数的符号。

如果您对数组进行操作,则可以不使用ByteBuffer, 例如,如下所示:

double[] doubles = new double[byteArray.length / 3];
for (int i = 0, j = 0; i != doubles.length; ++i, j += 3) {
  doubles[i] = (double)( (byteArray[j  ] & 0xff) | 
                        ((byteArray[j+1] & 0xff) <<  8) |
                        ( byteArray[j+2]         << 16));
}
Run Code Online (Sandbox Code Playgroud)

您将获得两个交错通道的样本,因此您可能需要随后将它们分开。

如果您有单声道,则不会有两个通道交错,而只有一次。对于 16 位,您可以使用byteBuffer.getShort(),对于 32 位,您可以使用byteBuffer.getInt()。但 24 位并不常用于计算,因此ByteBuffer没有相应的方法。如果您有未签名的样本,则必须屏蔽所有符号并抵消结果,但我猜未签名的 WAV 相当不常见。