aolsenjazz / libsamplerate-js

Resample audio in node or browser using a web assembly port of libsamplerate.
Other
32 stars 10 forks source link

Convert stereo audio to mono audio #142

Closed Riz-waan closed 7 months ago

Riz-waan commented 7 months ago

Hi!

I was just wondering if I can use this library to convert stereo audio to mono audio?

Thanks!

aolsenjazz commented 7 months ago

Hi, no that is not a part of the feature set. Fwiw, I asked ChatGPT to do this and it gave a pretty straightforward solution:

function convertStereoToMono(stereoSamples) {
  if (!stereoSamples || stereoSamples.length % 2 !== 0) {
    throw new Error("Input must be a 1xn Float32Array with even length.");
  }

  const monoSamplesLength = stereoSamples.length / 2;
  const monoSamples = new Float32Array(monoSamplesLength);

  for (let i = 0, j = 0; i < stereoSamples.length; i += 2, j++) {
    // Average the stereo samples to get mono samples
    monoSamples[j] = (stereoSamples[i] + stereoSamples[i + 1]) / 2;
  }

  return monoSamples;
}

given stereoSamples is a 1xn interleaved Float32 array where each sample is 0<n<1. Closing this issue as unrelated - happy coding!