【问题标题】:Why method for ByteBuffer putShort(value) does not working correctly in my case?为什么 ByteBuffer putShort(value) 的方法在我的情况下无法正常工作?
【发布时间】:2017-12-20 12:22:03
【问题描述】:

我的任务是将 short[] 数组转换为 byte[] 数组,因为需要通过套接字发送字节。这是 AudioTrack (Android) 的字节 对于转换使用这个post,特别是this 和this 当尝试将short转换为字节数组时,此方法只会产生白噪声:

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

但是这个转换工作正常:

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

为什么会这样?

【问题讨论】:

    标签: java android kotlin bytebuffer short


    【解决方案1】:

    byteBuf.array().size 将返回缓冲区的大小 (pcm.size * 2),无论是否将这么多字节写入缓冲区。你可能想要byteBuf.limit()。

    【讨论】:

    • @Sergey pcm.size * 2 的值是多少? byteBuf.limit() 的值是多少? pcm[i]的类型是什么?
    • type is short[] -- array ,所以当数组 short 转换为数组 byte 时,byte[] 的大小将是 size*2
    • @Sergey 拿一个short。通过putShort() 与put(byte[]) 运行它。告诉我们每个array() 的输入值和输出值。
    • 以后再做吧,现在没时间了。需要工作,对不起))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多