Skip to content
Advertisement

how to convert short array to byte array

I have found converting a short to byte array, and byte array to short array, but not short array to byte array.

Here is the code leading up to the conversion

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];

I have tried

              int i = 0;
              ByteBuffer byteBuf = ByteBuffer.allocate(N);
              while (buffer.length >= i) {
                  byteBuf.putShort(buffer[i]);
                  i++;
        }

bytes2 = byteBuf.array();

and

    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): obtainBuffer() track 0x30efa0 disabled, restarting

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): at java.nio.ShortBuffer.put(ShortBuffer.java:422)

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): at java.nio.ShortBuffer.put(ShortBuffer.java:391)

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));
            }

Advertisement

Answer

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++;
}
Advertisement