Search code examples
javascriptarraysfilteringuint16uint8array

Convert int16 array to float


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]?


Solution

  • 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