resample audio buffer from 44100 to 16000
No answers are correct. Here is the perfect code.
// `sourceAudioBuffer` is an AudioBuffer instance of the source audio
// at the original sample rate.
const DESIRED_SAMPLE_RATE = 16000;
const offlineCtx = new OfflineAudioContext(sourceAudioBuffer.numberOfChannels, sourceAudioBuffer.duration * DESIRED_SAMPLE_RATE, DESIRED_SAMPLE_RATE);
const cloneBuffer = offlineCtx.createBuffer(sourceAudioBuffer.numberOfChannels, sourceAudioBuffer.length, sourceAudioBuffer.sampleRate);
// Copy the source data into the offline AudioBuffer
for (let channel = 0; channel < sourceAudioBuffer.numberOfChannels; channel++) {
cloneBuffer.copyToChannel(sourceAudioBuffer.getChannelData(channel), channel);
}
// Play it from the beginning.
const source = offlineCtx.createBufferSource();
source.buffer = cloneBuffer;
source.connect(offlineCtx.destination);
offlineCtx.oncomplete = function(e) {
// `resampledAudioBuffer` contains an AudioBuffer resampled at 16000Hz.
// use resampled.getChannelData(x) to get an Float32Array for channel x.
const resampledAudioBuffer = e.renderedBuffer;
}
offlineCtx.startRendering();
source.start(0);
You can use an OfflineAudioContext to do the resampling, but you need to convert your data-uri to an ArrayBuffer first. This solution works in the browser, not on the server, as it's better to send lower quality audio (lower sample rate) on the network, than send a lot of data and resample on the server.
// `source` is an AudioBuffer instance of the source audio
// at the original sample rate.
var TARGET_SAMPLE_RATE = 16000;
var offlineCtx = new OfflineAudioContext(source.numberOfChannels,
source.duration * TARGET_SAMPLE_RATE,
TARGET_SAMPLE_RATE);
// Play it from the beginning.
var offlineSource = offlineCtx.createBufferSource();
offlineSource.buffer = source;
offlineSource.connect(offlineCtx.destination);
offlineSource.start();
offlineCtx.startRendering().then((resampled) => {
// `resampled` contains an AudioBuffer resampled at 16000Hz.
// use resampled.getChannelData(x) to get an Float32Array for channel x.
});