问题描述
我发现将short转换为字节数组,并且字节数组到短数组,但不是短数组到字节数组.
I have found converting a short to byte array, and byte array to short array, but not short array to byte array.
这是导致转换的代码
while(!stopped)
{
Log.i("Map", "Writing new data to buffer");
short[] buffer = buffers[ix++ % buffers.length];
N = recorder.read(buffer,0,buffer.length);
track.write(buffer, 0, buffer.length);
byte[] bytes2 = new byte[N];
我试过了
int i = 0;
ByteBuffer byteBuf = ByteBuffer.allocate(N);
while (buffer.length >= i) {
byteBuf.putShort(buffer[i]);
i++;
}
bytes2 = byteBuf.array();
和
ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(buffer);
但是我在两者上都收到此错误(错误如果不完全相同但两者非常相似):
However I receive this error on both (the error if not exactly the same but very similar for both):
05-29 13:41:12.021:W/AudioTrack(9758):获取缓冲区()轨道0x30efa0禁用,重新启动
05-29 13:41:12.857:W/AudioWorker(9758):读取语音时出错音频工作者
05-29 13:41:12.857: W/AudioWorker(9758): Error reading voice AudioWorker
05-29 13:41:12.857:W/AudioWorker(9758):java.nio.BufferOverflowException
05-29 13:41:12.857: W/AudioWorker(9758): java.nio.BufferOverflowException
05-29 13:41:12.857:W/AudioWorker(9758):在java.nio.ShortBuffer.put(ShortBuffer.java:422)
05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortBuffer.put(ShortBuffer.java:422)
05-29 13:41:12.857:W/AudioWorker(9758):在java.nio.ShortToByteBufferAdapter.put(ShortToByteBufferAdapter.java:210)
05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortToByteBufferAdapter.put(ShortToByteBufferAdapter.java:210)
05-29 13:41:12.857:W/AudioWorker(9758):在java.nio.ShortBuffer.put(ShortBuffer.java:391)
05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortBuffer.put(ShortBuffer.java:391)
05-29 13:41:12.857:W/AudioWorker(9758):在com.avispl.nicu.audio.AudioWorker.run(AudioWorker.java:126)
05-29 13:41:12.857: W/AudioWorker(9758): at com.avispl.nicu.audio.AudioWorker.run(AudioWorker.java:126)
为了提供尽可能多的信息,这里是使用字节数组之后的代码
And just to be give as much info as possible here is the code after that uses the byte array
Log.i("Map", "test");
//convert to ulaw
read(bytes2, 0, N);
//send to server
os.write(bytes2,0,bytes2.length);
System.out.println("bytesRead "+buffer.length);
System.out.println("data "+Arrays.toString(buffer));
}
推荐答案
Java short
是 16 位类型,byte
是 8 位类型.您有一个循环尝试将 N
短片插入 N
字节长的缓冲区中;它需要 2*N
字节长以适合您的所有数据.
Java short
is a 16-bit type, and byte
is an 8-bit type. You have a loop that tries to insert N
shorts into a buffer that's N
-bytes long; it needs to be 2*N
bytes long to fit all your data.
ByteBuffer byteBuf = ByteBuffer.allocate(2*N);
while (N >= i) {
byteBuf.putShort(buffer[i]);
i++;
}
这篇关于如何将短数组转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!