Converting Float32Array to Int16Array

I want to convert Float32Array to Int16Array .

Here's what I have (I don't provide data

).

  var data = ...; /*new Float32Array();*/
  var dataAsInt16Array = new Int16Array(data.length);
  for(var i=0; i<data.length; i++){
    dataAsInt16Array[i] = parseInt(data[i]*32767,10);
  }

      

I'm not sure if I'm doing this right and looking for some direction.

+3


source to share


5 answers


You can do it directly from ArrayBuffer

var dataAsInt16Array = new Int16Array(data.buffer);

      




var f32 = new Float32Array(4);
f32[0] = 0.1, f32[1] = 0.2, f32[2] = 0.3, f32[3] = 0.4;
// [0.10000000149011612, 0.20000000298023224, 0.30000001192092896, 0.4000000059604645]

var i16 = new Int16Array(f32.buffer);
// [-13107, 15820, -13107, 15948, -26214, 16025, -13107, 16076]

// and back again
new Float32Array(i16.buffer);
// [0.10000000149011612, 0.20000000298023224, 0.30000001192092896, 0.4000000059604645]

      

+5


source


If, after transforming the raw underlying data, you can use the approach described by Pavel S. in his answer.

But keep in mind that you will not get the same numbers as the IEEE 754 32-bit representation of that number in the case of Float32. When a new kind is used such as Int16, you are looking at the binary representation of that, not the original number.



If you are behind the number, you have to convert manually, just change your code to:

var data = ...; /*new Float32Array();*/
var len = data.length, i = 0;
var dataAsInt16Array = new Int16Array(len);

while(i < len)
  dataAsInt16Array[i] = convert(data[i++]);

function convert(n) {
   var v = n < 0 ? n * 32768 : n * 32767;       // convert in range [-32768, 32767]
   return Math.max(-32768, Math.min(32768, v)); // clamp
}

      

+4


source


    var floatbuffer = audioProcEvent.inputBuffer.getChannelData(0);
    var int16Buffer = new Int16Array(floatbuffer.length);

    for (var i = 0, len = floatbuffer.length; i < len; i++) {
        if (floatbuffer[i] < 0) {
            int16Buffer[i] = 0x8000 * floatbuffer[i];
        } else {
            int16Buffer[i] = 0x7FFF * floatbuffer[i];
        }
    }

      

+1


source


You seem to be trying to not only convert the data format, but also process the original data and store it in a different format.

The direct way to convert Float32Array

to Int16Array

is as easy as

var a = new Int16Array(myFloat32Array);

      

For processing data, you can use the approach you indicated in the question. I'm not sure what to call parseInt

.

0


source


ECMAScript 2015 onwards has TypedArray.from

one that converts any typed array (and indeed any iterable) to a specified typed array type.

So converting Float32Array to Uint8Array is now as easy as:

const floatArray = new Float32Array()
const intArray = Int16Array.from(floatArray)

      

... albeit truncated.

0


source







All Articles