1

我在尝试将短值转换为字节 [2] 时遇到了一些问题。我正在使用它对某些音频数据缓冲区进行一些转换(将增益应用于缓冲区)。首先,我像这样加载音频缓冲区:

mRecorder.read(buffer, 0, buffer.length);

缓冲区在哪里

private byte[] buffer;

然后,我得到了样本(录音是 16 位样本大小),如下所示:

short sample = getShort(buffer[i*2], buffer[i*2+1]);

getShort 的定义如下:

/* 
 * 
 * Converts a byte[2] to a short, in LITTLE_ENDIAN format
 * 
 */
private short getShort(byte argB1, byte argB2)
{
    return (short)(argB1 | (argB2 << 8));
}

然后我将增益应用于样本:

sample *= rGain;

在此之后,我尝试从相乘的样本中取回字节数组:

byte[] a = getByteFromShort(sample);

但这失败了,因为即使增益为 1,声音也有很多噪音。

下面是 getByteFromShort 方法定义:

    private byte[] getByteFromShort(short x){
//variant 1 - noise
    byte[] a = new byte[2];
    a[0] = (byte)(x & 0xff);
    a[1] = (byte)((x >> 8) & 0xff);

//variant 2 - noise and almost broke my ears - very loud
//      ByteBuffer buffer = ByteBuffer.allocate(2);
//      buffer.putShort(x);
//      buffer.flip();

    return a;
}

所以问题在于将短值转换为字节[2]。当增益为 1.0 时,声音充满了噪音。

以下是完整的增益应用方法:

for (int i=0; i<buffer.length/2; i++)
{ // 16bit sample size                      
    short curSample = getShort(buffer[i*2], buffer[i*2+1]);
if(rGain != 1){
    //apply gain
    curSample *= rGain;
    //convert back from short sample that was "gained" to byte data
    byte[] a = getByteFromShort(curSample);
    //modify buffer to contain the gained sample
    buffer[i*2] = a[0];
    buffer[i*2 + 1] = a[1];
}

   }

你们能否看看 getByteFromShort 方法并告诉我我错在哪里?

谢谢。

4

4 回答 4

5

getByteFromShort()似乎还可以。

getShort(byte argB1, byte argB2)是错的。当 argB1 为负时,它会产生不正确的结果。

它应该是

return (short)((argB1 & 0xff) | (argB2 << 8));
于 2012-05-11T12:39:21.343 回答
0

使用以下代码:

ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);
于 2012-05-11T10:59:00.927 回答
0

我会使用 ByteBuffer

ByteBuffer buffer = ByteBuffer.allocate(8*1024);
mRecorder.read(buffer.array(), 0, buffer.capacity());
// using NIO
mRecorder.read(buffer);

while(buffer.remaining() > 1) {
    short s = bb.getShort(x);
    // do something with s
}
于 2012-05-11T11:50:48.713 回答
0

ByteBuffer 及其在 java.nio 中的同类可以帮助解决这个问题。基本上,您将使用您的数据创建一个由数组支持的 ByteBuffer ByteBuffer.wrap(array)。然后,您可以设置缓冲区的字节顺序,ByteBuffer.order()并使用 get/put Int/Short/byte... 等函数来操作底层数组中的数据。

于 2012-05-11T11:52:57.850 回答