resample audio buffer from 44100 to 16000

Mahendra Garg picture Mahendra Garg · Dec 22, 2014 · Viewed 10.1k times · Source

I have audio data in format of data-uri, then I converted this data-uri into a buffer now I need this buffer data in new samplerate, currently audio data is in 44.1khz and I need data in 16khz, and If I recorded the audio using RecordRTC API and if I record audio in low sample rate then I got distorted audio voice, So I am not getting how to resample my audio buffer,

If any of you any idea regarding this then please help me out.

Thanks in advance :)

Answer

padenot picture padenot · Dec 22, 2014

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