在 javascript 中对 PCM 音频缓冲区进行下采样

Downsampling a PCM audio buffer in javascript

我正在尝试对从 audioContext 获得的采样率进行下采样。我相信它会在 44100 进入,我希望它是 11025。我想我可以平均每 3 个样本并且它以正确的速率播放,但是音调太高了,好像我们都在氦气上.

以 11025 个样本将 float32Array 从 44100 下采样到 int16Array 的正确方法是什么。

var context = new Flash.audioContext();
var audioInput = context.createMediaStreamSource(stream);
var recorder = context.createScriptProcessor(null, 1, 1);
recorder.onaudioprocess = onAudio;
audioInput.connect(recorder);
recorder.connect(context.destination);

var onAudio = function (e) {
    var left = e.inputBuffer.getChannelData(0);
    bStream.write(Flash.convertFloat32ToInt16(left));
}

var convertFloat32ToInt16 = function(buffer) {
    var l = buffer.length;
    var point = Math.floor(l/3);
    var buf = new Int16Array(point);
    for (var x = l; x > 0;) {
        var average = (buffer[x] + buffer[x-1] +  buffer[x-2]) / 3;
        buf[point] = average*0x7FFF;
        point -= 1;
        x -= 3;
    }
    return buf.buffer;
}

对于任何其他需要答案的人。

var downsampleBuffer = function (buffer, sampleRate, outSampleRate) {
    if (outSampleRate == sampleRate) {
        return buffer;
    }
    if (outSampleRate > sampleRate) {
        throw "downsampling rate show be smaller than original sample rate";
    }
    var sampleRateRatio = sampleRate / outSampleRate;
    var newLength = Math.round(buffer.length / sampleRateRatio);
    var result = new Int16Array(newLength);
    var offsetResult = 0;
    var offsetBuffer = 0;
    while (offsetResult < result.length) {
        var nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
        var accum = 0, count = 0;
        for (var i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
            accum += buffer[i];
            count++;
        }

        result[offsetResult] = Math.min(1, accum / count)*0x7FFF;
        offsetResult++;
        offsetBuffer = nextOffsetBuffer;
    }
    return result.buffer;
}

这将 return 采样率小于传递给它的采样率,同时还将其转换为 int16Array 而不是 float32。