0

I was using below code for downsampling my audio while recording

let inputSampleRate; let inputBuffer = [];

function init(x) {
     inputSampleRate = x; 
}

function process(inputFrame) {
     for (let i = 0; i < inputFrame.length; i++) {
        inputBuffer.push((inputFrame[i]) * 32767);
     }

     const PV_SAMPLE_RATE = 16000;
     const PV_FRAME_LENGTH = 512;
 
     while ((inputBuffer.length * PV_SAMPLE_RATE / inputSampleRate) > PV_FRAME_LENGTH) {
        let outputFrame = new Int16Array(PV_FRAME_LENGTH);
        let sum = 0;
        let num = 0;
        let outputIndex = 0;
        let inputIndex = 0;

        while (outputIndex < PV_FRAME_LENGTH) {
            sum = 0;
            num = 0;
            while (inputIndex < Math.min(inputBuffer.length, (outputIndex + 1) * inputSampleRate / PV_SAMPLE_RATE)) {
                sum += inputBuffer[inputIndex];
                num++;
                inputIndex++;
            }
            outputFrame[outputIndex] = sum / num;
            outputIndex++;
        }

        postMessage(outputFrame);

        inputBuffer = inputBuffer.slice(inputIndex);
    } 
}

Can anyone please suggest how can I edit this one, so that it can be used to upsample my audio from 8k to 16k?

Mrityunjoy
  • 17
  • 4

1 Answers1

2

The traditional way to do upsampling (and downsampling) can be found at Wikipedia article about upsampling.

If you want something really cheap and dirty, just linearly interpolate between samples. So if you have samples x0 and x1, the upsampled values are y0=x0, y2=x1, and the new sample y1=(x0+x1)/2. This isn't great and you might hear artifacts.

Edit:

In your code, you can try something like this:

s0 = inputBuffer[inputIndex];
s1 = inputBuffer[inputIndex + 1];
outputFrame[outputIndex] = s0;
outputFrame[outputIndex + 1] = (s0 + s1)/2;
outputFrame[outputIndex + 2] = s1

You'll have to keep track of the indices so you don't try to access beyond the length of the arrays. This is totally untested.

Raymond Toy
  • 5,490
  • 10
  • 13
  • Thank you for your response sir. I understand what you're saying but can you suggest how I can apply that in the code I've attached, just what changes in the calculation part is needed. – Mrityunjoy Jul 16 '20 at 10:19
  • I think it would be something like this: – Raymond Toy Jul 16 '20 at 13:59
  • I tried completing my code, please have a look. "function init(x) { inputSampleRate = x; } function process(inputFrame) { for (let i = 0; i < inputFrame.length; i++) { inputBuffer.push((inputFrame[i]) * 32767); } const PV_FRAME_LENGTH = 512; for (let inputIndex = 0; inputIndex – Mrityunjoy Jul 16 '20 at 17:58
  • Please create a snippet at jsfiddle.net or codepen.com or whatever. Then you can share it and then I can look at it and provide more feedback. Use, perhaps, a sinewave as the input. The output should like like a sinewave, of course. – Raymond Toy Jul 16 '20 at 18:02