我在尝试将短值转换为字节 [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 方法并告诉我我错在哪里?
谢谢。