javascriptweb-audio-apityped-arrays

Javascript: UInt8Array to Float32Array


I have some audio buffer in usigned 8bit PCM format need to play via web audio which only accept signed 32bit PCM. And now I have ArrayBuffer for pieces of pcm_u8 data(come from Uint8array). How can I convert it to Float32Array?


Solution

  • This function converts an ArrayBuffer to Float32Array

    function convertBlock(buffer) { // incoming data is an ArrayBuffer
        var incomingData = new Uint8Array(buffer); // create a uint8 view on the ArrayBuffer
        var i, l = incomingData.length; // length, we need this for the loop
        var outputData = new Float32Array(incomingData.length); // create the Float32Array for output
        for (i = 0; i < l; i++) {
            outputData[i] = (incomingData[i] - 128) / 128.0; // convert audio to float
        }
        return outputData; // return the Float32Array
    }
    

    This one converts a Uint8Array to Float32Array

    function convertBlock(incomingData) { // incoming data is a UInt8Array
        var i, l = incomingData.length;
        var outputData = new Float32Array(incomingData.length);
        for (i = 0; i < l; i++) {
            outputData[i] = (incomingData[i] - 128) / 128.0;
        }
        return outputData;
    }
    

    Note: A few months after writing this answer, Safari finally caught up and made the TypedArray.from method available (as noted in another answer)

    So, the code would be simply (for an ArrayBuffer input)

    const convertBlock = input => Float32Array.from(new Uint8Array(input), v => (v - 128) / 128);
    

    For Uint8Array input, you could still use the above, or simpler:

    const convertBlock = input => Float32Array.from(input, v => (v - 128) / 128);