0

My task is convert short[] array to byte[] array, because need send bytes via socket. This is bytes for AudioTrack (Android) For converting use this post, specifically this and this This method gives only white noise, when try to convert short to byte array:

 val sampleBuffer = decoder.decodeFrame(frameHeader, bitstream) as SampleBuffer
 val pcm = sampleBuffer.buffer //pcm is short[] array 

byteBuf = ByteBuffer.allocate(pcm.size * 2) // because 1 short = 2 bytes

while (pcm.size > i) {
   byteBuf.putShort(pcm[i]) 
   i++ 
}

auddioTrack.write(byteBuf.array(), 0, byteBuf.limit());

But this convert works fine:

var i = 0
    val byteBuf = ByteBuffer.allocate(pcm.size * 2)
    val buff =  ByteBuffer.allocate(2)

    //pcm size equals 2304
    while (pcm.size > i) {
       // byteBuf.putShort(pcm[i])
      byteBuf.put(byteArrayOf((pcm[i].toInt() and 0x00FF).toByte(), ((pcm[i].toInt() and 0xFF00) shr (8)).toByte()))                       
     i++
    }

auddioTrack.write(byteBuf.array(), 0, byteBuf.limit());

Why has it happened?

Serg Burlaka
  • 2,351
  • 24
  • 35

1 Answers1

0

byteBuf.array().size will return the size of the buffer (pcm.size * 2) regardless of whether that many bytes were written into the buffer. You probably want byteBuf.limit() instead.

Gili
  • 86,244
  • 97
  • 390
  • 689
  • @Sergey What is the value of `pcm.size * 2`? What is the value of `byteBuf.limit()`? What is the type of `pcm[i]`? – Gili Dec 20 '17 at 12:35
  • type is short[] -- array , so when convert array short to array byte, size of byte[] will be size*2 – Serg Burlaka Dec 20 '17 at 12:40
  • @Sergey Take a single `short`. Run it through `putShort()` versus `put(byte[])`. Tell us the input value, and the output value you get in each `array()`. – Gili Dec 20 '17 at 12:46
  • wiil do it later, now there is no time. need to work, sorry)) – Serg Burlaka Dec 20 '17 at 12:48