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?

user7597554
  • 95
  • 4
  • 11

1 Answers1

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.

neeh
  • 2,777
  • 3
  • 24
  • 32
  • 1
    You could even reuse the buffer if you wanted. `return new type(src.buffer)`. – Ian MacDonald Nov 14 '18 at 16:48
  • this is amazing! thank you so much for this. improved my onderstanding of buffers – Unispaw Jan 28 '20 at 09:50
  • 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` – Ben Butterworth May 11 '21 at 14:29
  • I don't think the Note applies as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/buffer 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 – SollyBunny May 31 '23 at 11:20