![](/img/trans.png)
[英]How to convert libGDX's Texture to byte array and back again in Java
[英]byte array to short array and back again in 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++;
}
我已经做了我能想到的所有工作来完成这项工作,但我最接近的是让它在所有其他编码/解码中工作,我不知道为什么。 谢谢你的帮助。
我还建议您尝试 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);
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();
}
一些 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());
}
byte[2] bytes;
int r = bytes[1] & 0xFF;
r = (r << 8) | (bytes[0] & 0xFF);
short s = (short)r;
您的代码正在做小端短裤,而不是大。 您已经交换了 MSB 和 LSB 的索引。
由于您使用的是 big-endian short,因此您可以在另一端使用包裹在 ByteArrayInputStream(和 DataOutputStream/ByteArrayOutputStream)上的 DataInputStream,而不是自己进行解码。
如果您让所有其他解码都正常工作,我猜您有奇数个字节,或者其他地方的一个错误导致您的错误在每隔一次通过时得到修复。
最后,我会用 i+=2 遍历数组并使用 MSB= arr[i] 和 LSB=arr[i+1] 而不是乘以 2,但这只是我。
看起来您正在读取字节和写回字节之间交换字节顺序(不确定这是否是故意的)。
public static short getShortValue(byte a, byte b) {
return (short) (b << 8 | a & 0xFF);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.