Convert int16 array to float

2019-08-05 14:01发布

I have an array of bytes from an audio file and I want to convert it into data that I can process to filter the audio signal. I have an array like this: [239,246,96,247.....]; Each element is a uint8 byte

Each 2 bytes(16 bits) represent a sample,so I converted this array into a int16 element array.

How can I then convert this array into a signal with values in the range[-1,1]?

2条回答
Luminary・发光体
2楼-- · 2019-08-05 14:14

You already have your signed int16's so you just have to divide by the min and max int16 value respective to the sign.

let buffer = new Int16Array([0x0001, 0x7fff, 0x000, 0xffff, 0x8000]);
// [1, 32767, 0, -1, -32768]
let result = new Float32Array(buffer.length);
for(let i=0; i<buffer.length; i++) result[i] = buffer[i] / (buffer[i] >= 0 ? 32767 : 32768);
console.log(result[0], result[1], result[2], result[3], result[4]);
// 0.000030518509447574615 1 0 -0.000030517578125 -1
查看更多
神经病院院长
3楼-- · 2019-08-05 14:21

x is an element of my array. x should be uint16 and not int16.

Next foreach x, you have to do (x - maxUInt16/2) / maxUInt16/2

So => y = (x - (2^15 - 1)) / (2^15 - 1)

maxUint16 is impair so you have to handle possible overflow

Code :

let init = new Uint8Array(22);

for (let i = 0; i < 16; i++) {
    init[i] = Math.trunc(Math.random() * 255) % 255;
}
/* Interested test case */
init[16] = 0;
init[17] = 0;    // Should return -1
init[18] = 255;
init[19] = 255;  // Should return 1
init[20] = 127;
init[21] = 255;  // Should return 0

let sample = new Uint16Array(11);

for (let i = 0; i < 11; i++) {
    sample[i] = (init[i*2] << 8) | init[i*2+1];
}

let ranged = [];

for (let i = 0; i < 11; i++) {
     ranged.push(Math.min(( Number(sample[i]) -  32767) / 32767 , 1));
}

console.log(init);
console.log(sample);
console.log(ranged);
查看更多
登录 后发表回答