在javascript中对PCMaudio缓冲区进行降采样

我正在尝试从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; } 

       

网上收集的解决方案 "在javascript中对PCMaudio缓冲区进行降采样"

对于任何需要答案的人

 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; } 

这将返回一个小于传递给它的采样率,同时也将其转换为int16Array而不是float32。