arseneyr / wasm-media-encoders

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

Example browser/mic demo #9

Open s1239u85 opened 2 years ago

s1239u85 commented 2 years ago

Is there a simple browser demo available? I am trying to get it to work with the microphone.

skidnight commented 1 year ago

If you already have the WebAudio nodes setup, the encoder takes a Float32Array of PCM data.

Here is it being used with a script processor, it works very well at least for my purposes.

        this.#scriptProcessorNode.onaudioprocess = (event) => {

            var sourceAudioBuffer = event.inputBuffer;  // directly received by the audioprocess event from the microphone in the browser

            let currentData = this.#encoder?.encode([sourceAudioBuffer]);

            if(currentData == undefined || currentData.length == 0) {
                return; // Nothing encoded
            }

            // Append new data to the oggData (Uint8Array) buffer
            this.#oggData.set(currentData, this.#offset);
            this.#offset += currentData.length; // Keeping track of the offset for appending
        }

You can stream the data into the encoder like above and when you're done just call finalize on the encoder to get the last data. just make sure to not try and reuse the encoder after calling finalize or else you will get corrupt data (in my experience)

Hope this helps.