Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
Wilson Luniz Avatar asked Jan 08 '16 04:01

Wilson Luniz


People also ask

What is JavaScript Uint8Array?

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Is Uint8Array an ArrayBuffer?

Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.

What is Float32Array?

The Float32Array typed array represents an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0 .

What is ArrayBuffer in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".


2 Answers

This function converts an ArrayBuffer to Float32Array

var 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

var 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;
}
like image 83
Jaromanda X Avatar answered Oct 16 '22 20:10

Jaromanda X


ECMAScript 2015 and onwards has TypedArray.from which converts any typed array (and indeed, any iterable) to the specified typed array format.

So converting a Uint8Array to a Float32Array is now as easy as:

const intArray = new Uint8Array()
const floatArray = Float32Array.from(intArray)
like image 20
robjtede Avatar answered Oct 16 '22 20:10

robjtede