1
$\begingroup$

I'm looking everywhere for solutions for audio downsampling. However for one reason or another they are incomplete, sometimes buggy, and sometimes are in a programming language I cannot understand.

So here's my use case:

I have an array containing two channels (left-right, it is a microphone) with Float32 data that gets interleaved and then converted to PCM like this:

function interleave(left, right) {
    var length = left.length + right.length;
    var result = new Float32Array(length);
    var _index = 0;
    for(var index = 0; index < length;) {
        result[index++] = left[_index];
        result[index++] = right[_index];
        _index++;
    }
    return result;
}

function convertToPCM(raw) {
    var output = new Buffer(raw.length*2);
    for (var i = 0, offset = 0; i < raw.length; i++, offset += 2){
        var s = Math.max(-1, Math.min(1, raw[i]));
        output.writeInt16LE(s < 0 ? s*0x8000 : s*0x7FFF, offset);
    }
    return output;
}

This is NodeJS\Javascript, but I think it's pretty clear how it works.

Now here's the issue. The output of these function needs to generate a WAV file downsampled to 22000 or 16000, but the source has a sample rate of 44100.

Could you please highlight what algorithm should I use in order to achieve this?

Thank you very much!

$\endgroup$
1
$\begingroup$

Breaking down the conversion into an upsampling and a downsampling step as explained in mbaz's answer is not necessary - band-limited interpolation achieves the same result in one single process, for any conversion ratio, and its quality is easy to fine-tune (through various approximations of the band-limited pulse).

libsamplerate is an example of open-source implementation that does not rely on upsampling/downsampling. It should be possible to bind it to NodeJS through an add-on, or even to rewrite it in javascript - once stripped of the code handling corner cases (variable rate, compensation of processing delay), the code fits in a 50-line loop.

$\endgroup$
  • $\begingroup$ one thing about bandlimited sample rate conversion is that there is a qualitative difference between upsampling and downsampling. in upsampling, the Nyquist frequency is increased and the frequency band between the old and new Nyquist is (or should be) set to zero. because of the loss of bandwidth that comes with downsampling, additional low-pass filtering is needed so to prevent aliasing. there is a way to do both that low-pass filtering and the polyphase interpolation in one step, but it still is qualitatively different than when we upsample. $\endgroup$ – robert bristow-johnson Nov 15 '14 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.