1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You could even reuse the buffer if you wanted. return new type(src.buffer).
this is amazing! thank you so much for this. improved my onderstanding of buffers
If you have const floats = new Float32Array([1.53, 1000.5]), using new Uint8Array(floats) will give you [1, 232], so be careful. Only in certain circumstances will you want your floats to be wrap back around 255. i.e. 232 was gotten by doing 1000-256-256-256
I don't think the Note applies as developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… says "The buffer property is an accessor property whose set accessor function is undefined, meaning that you can only read this property" which is quiet annoying

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.