arseneyr / wasm-media-encoders

MP3 and Ogg Vorbis encoders for the browser and Node
MIT License
34 stars 4 forks source link

Example is incomplete #1

Closed marcusstenbeck closed 4 years ago

marcusstenbeck commented 4 years ago

Hey, the example in the readme is incomplete. There's a variable moreData that isn't defined or assigned anywhere.

Example usage

createMp3Encoder().then((encoder) => {
  encoder.configure({
    sampleRate: 48000,
    channels: 2,
    vbrQuality: 2,
  });

  let outBuffer = new Uint8Array(1024 * 1024);
  let offset = 0;

  while (true) {
    const mp3Data = moreData
      ? encoder.encode([
          pcm_l /* Float32Array of left channel PCM data */,
          pcm_r /* Float32Array of right channel PCM data */,
        ])
      : /* finalize() returns the last few frames */
        encoder.finalize();

    /* mp3Data is a Uint8Array that is still owned by the encoder and MUST be copied */

    while (mp3Data.length + offset > outBuffer.length) {
      const newBuffer = new Uint8Array(outBuffer.length * 2);
      newBuffer.set(outBuffer);
      outBuffer = newBuffer;
    }

    outBuffer.set(mp3Data, offset);
    offset += mp3Data.length;

    if (!moreData) {
      break;
    }
  }

  return new Uint8Array(outBuffer.buffer, 0, offset);

  /* Or encoder can be reused without calling createEncoder() again:

  encoder.configure({...new params})
  encoder.encode()
  encoder.finalize() */
});
arseneyr commented 4 years ago

Yeah, I was kinda going for the notion that encode() may be called repeatedly but I suppose it wasn't very clear. I've updated the example to include a moreData variable.

marcusstenbeck commented 4 years ago

Nice—I was able to figure it out and make a small prototype with it for injecting one audio file in the middle of another.

https://b0zck.csb.app/