libopusjs
libopusjs copied to clipboard
a libopus API for JavaScript (wasm/asm.js)
ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[]
= libopusjs
This project is mostly about having access to the low-level packet encoding/decoding API of libopus in JavaScript. + Opus allow to encode audio without container and can handle packet loss, which makes it very suitable for VoIP over UDP (it also has voice optimizations).
== API
[source, js]
// Encoder
// create encoder // channels: 1-2 // samplerate: 8000,12000,16000,24000,48000 // bitrate: see Opus recommended bitrates // frame_size: frame size in milliseconds (2.5,5,10,20,40,60), 20 is recommended // voice_optimization: true/false Encoder(channels, samplerate, bitrate, frame_size, voice_optimization)
// free encoder memory Encoder.destroy()
// add samples to the encoder buffer // samples: Int16Array of interleaved (if multiple channels) samples Encoder.input(samples)
// output the next encoded packet // return Uint8Array (valid until the next output call) or null if there is no packet to output Encoder.output()
// Decoder
// create decoder // channels and samplerate should match the encoder options Decoder(channels, samplerate)
// free decoder memory Decoder.destroy()
// add packet to the decoder buffer // packet: Uint8Array Decoder.input(packet)
// output the next decoded samples // return samples (interleaved if multiple channels) as Int16Array (valid until the next output call) or null if there is no output Decoder.output()
== Loading
[NOTE]
You can use the asm.js
or wasm
version, the WebAssembly is much faster in nodejs/browser than the asm.js version on my computer. asm.js
also has limited memory.
Since the WebAssembly version will need to load the .wasm
file, a url scheme like http
is required and the library will be asynchronously loaded. It will load the libopus.wasm
file relative to libopus.wasm.js
, unless the global LIBOPUS_WASM_URL
exists (containing the URL).
libopus.loaded
will be true when loaded and libopus.onload
will be called if defined. Using asm.js, libopus.onload
will probably never be called because it was not yet defined. See link:examples/test[].
[horizontal]
.Files
asm.js:: dist/libopus.asm.js
wasm:: dist/libopus.wasm.js dist/libopus.wasm
== Usage
Input data to the encoder or the decoder, then loop over the output call until it returns null. A single input can give multiple outputs or none.
See link:examples/test[].
[source,js]
// nodejs: var libopus = require("./libopus.js");
// in browser: // load the script, libopus will be available as a global
// create encoder var enc = new libopus.Encoder(1,48000,24000,false);
// create decoder var dec = new libopus.Decoder(1,48000);
// destroy encoder enc.destroy();