Web音频API在Javascript中下采样44.1 khz

时间:2014-12-10 22:12:51

标签: audio getusermedia downsampling recorder.js

我使用RecorderJS录制来自用户的麦克风流。默认导出是44.1 kHz,16位的WAV文件。无论如何我可以将其下采样到11kHz或16kHz而不听起来很奇怪吗?   无论如何我只能使用javascript从Web Audio API getUserMedia流中获取16bit 16khz WAV文件吗?

我试图减小文件大小,从而为用户节省了大量带宽。感谢。

1 个答案:

答案 0 :(得分:1)

编辑:还有一件事,你也可以只发送一个频道而不是两个频道......

我不确定这是不是正确的方法,但我做了插入从麦克风收到的数据, 我猜,你正在用麦克风捕捉你的数据,

 this.node.onaudioprocess = function(e){
      if (!recording) return;
      worker.postMessage({
           command: 'record',
           buffer: [
                e.inputBuffer.getChannelData(0),
                e.inputBuffer.getChannelData(1)
                ]
      });
  }

现在将其修改为

var oldSampleRate = 44100, newSampleRate = 16000;
this.node.onaudioprocess = function(e){

    var leftData = e.inputBuffer.getChannelData(0);
    var rightData = e.inputBuffer.getChannelData(1);
    leftData = interpolateArray(leftData, leftData.length * (newSampleRate/oldSampleRate)  );
    rightData = interpolateArray(rightData, rightData.length * (newSampleRate/oldSampleRate) );
    if (!recording) return;
    worker.postMessage({
         command: 'record',
         buffer: [
              leftData,
              rightData
              ]
    });
}

function interpolateArray(data, fitCount) {
    var linearInterpolate = function (before, after, atPoint) {
        return before + (after - before) * atPoint;
    };

    var newData = new Array();
    var springFactor = new Number((data.length - 1) / (fitCount - 1));
    newData[0] = data[0]; // for new allocation
    for ( var i = 1; i < fitCount - 1; i++) {
        var tmp = i * springFactor;
        var before = new Number(Math.floor(tmp)).toFixed();
        var after = new Number(Math.ceil(tmp)).toFixed();
        var atPoint = tmp - before;
        newData[i] = linearInterpolate(data[before], data[after], atPoint);
    }
    newData[fitCount - 1] = data[data.length - 1]; // for new allocation
    return newData;
};