Float32 to Int16 - Javascript (web audio API)

I am trying to convert Float32 to Int16. But for now, this is ineffective. Since the output sound will generate a lot of clipping (so very poor audio output). I am using this function:

function convertoFloat32ToInt16(buffer) {
  var l = buffer.length;  //Buffer
  var buf = new Int16Array(l/3);

  while (l--) {
    if (l==-1) break;

    if (buffer[l]*0xFFFF > 32767)
      buf[l] = 32767;
    elseif (buffer[l]*0xFFFF < -32768)
      buf[l] = -32768;
    else 
      buf[l] = buffer[l]*0xFFFF;
  }
  return buf.buffer;
}

If gainNode () was previously implemented , the clipping effect would be less noticeable. But this is not desirable, because the goal should be effective in every microphone. The clipping effect is displayed on this Matlab graph:

clipping effect

+4
source share
1 answer

Replacing while with this is the solution:

while (l--) {
    s = Math.max(-1, Math.min(1, samples[l]));
    buf[l] = s < 0 ? s * 0x8000 : s * 0x7FFF;
    //buf[l] = buffer[l]*0xFFFF; //old   //convert to 16 bit
  }
}

The recordings now sound perfect, and the Matlab graphics -

+3
source

Source: https://habr.com/ru/post/1616081/


All Articles