在我的例子中,Chrome 以 96kHz 录制音频,Firefox 以 44.1kHz 录制音频,这会产生巨大的WAV文件。我在 recorderWorker.js 中实现了一个下采样功能,您可以在其中选择所需的采样率,例如 16000。
function downsampleBuffer(buffer, rate) {
if (rate == sampleRate) {
return buffer;
}
if (rate > sampleRate) {
throw "downsampling rate show be smaller than original sample rate";
}
var sampleRateRatio = sampleRate / rate;
var newLength = Math.round(buffer.length / sampleRateRatio);
var result = new Float32Array(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] = accum / count;
offsetResult++;
offsetBuffer = nextOffsetBuffer;
}
return result;
}
我在导出 wav 文件时调用它:
function exportWAV(rate, type) {
var bufferL = mergeBuffers(recBuffersL, recLength);
var bufferR = mergeBuffers(recBuffersR, recLength);
var interleaved = interleave(bufferL, bufferR);
var downsampledBuffer = downsampleBuffer(interleaved, rate);
var dataview = encodeWAV(rate, downsampledBuffer, false);
var audioBlob = new Blob([ dataview ], {
type : type
});
this.postMessage(audioBlob);
}