6

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.

1 Answer 1

20

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This is great, I've been looking for a method like this for JavaScript. Just out of curiosity, can this be slightly adjusted to get the 'spline' interpolation, or does it require extensive reproduction?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.