Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : interpolate an array of numbers

few months back, I was looking for a way to downsample the audio data captured from mic using HTML5. I needed output rate as 12000Hz, if input was a direct multiplication of that (i.e 48000Hz) I had no problem, but it seemed complicated for other rates( e.g 44100Hz).

In these scenarios, direct down sampling( retaining only 1 out every 4) won't work, so I thought of interpolation, but stackoverflow had no solution at that time. So answering it myself.

like image 679
mido Avatar asked Nov 15 '14 00:11

mido


1 Answers

the source of my solution.

the fiddle demo.

the code for interpolating arrays,

function interpolateArray(data, fitCount) {

    var linearInterpolate = function (before, after, atPoint) {
        return before + (after - before) * atPoint;
    };

    var newData = new Array();
    var springFactor = new Number((data.length - 1) / (fitCount - 1));
    newData[0] = data[0]; // for new allocation
    for ( var i = 1; i < fitCount - 1; i++) {
        var tmp = i * springFactor;
        var before = new Number(Math.floor(tmp)).toFixed();
        var after = new Number(Math.ceil(tmp)).toFixed();
        var atPoint = tmp - before;
        newData[i] = linearInterpolate(data[before], data[after], atPoint);
    }
    newData[fitCount - 1] = data[data.length - 1]; // for new allocation
    return newData;
};

example of using it:

var originalArry = [1,5,3];
var newArry = interpolateArray([1,5,3],5);
like image 77
mido Avatar answered Sep 25 '22 10:09

mido