Convert float values to uint8 array in javascript

2019-07-30 16:32发布

问题:

I have a Float32Array with values from an audio file.I want to save it as a .wav file so I need to convert that values to a Uint8array.

To convert from uint8 to float I convert first to an int16 array and then to a Float32Array (Convert int16 array to float) How can I do that conversion in the other direction?

回答1:

You can convert to an ArrayBuffer, copy the data into and then create a byte view of this buffer :

var data = new Float32Array([0.1, 0.2, 0.3]);

var buffer = new ArrayBuffer(data.byteLength);
var floatView = new Float32Array(buffer).set(data);
var byteView = new Uint8Array(buffer);

This function can convert any TypedArray to any other kind of TypedArray :

function convertTypedArray(src, type) {
    var buffer = new ArrayBuffer(src.byteLength);
    var baseView = new src.constructor(buffer).set(src);
    return new type(buffer);
}

Example :

convertTypedArray(new Float32Array([0.5, 0.3, -0.1]), Uint8Array);

Edit

As Ian pointed out in the comment section, you can access the ArrayBuffer with TypedArray.buffer, so you can simply do :

var byteArray = new Uint8Array(floatArray.buffer);

Note that doing this, byteArray and floatArray will share the same buffer, so modifying byteArray will modify floatArray and vice versa.