![](/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.