Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
ogg-opus-decoder
Advanced tools
The ogg-opus-decoder npm package is a JavaScript library that allows you to decode Ogg Opus audio files. It is useful for applications that need to handle audio streaming or playback in the browser or in Node.js environments.
Decoding Ogg Opus Files
This feature allows you to decode an Ogg Opus file and output the raw PCM data. The code sample demonstrates how to set up a stream to read an Ogg Opus file, decode it, and write the decoded PCM data to an output file.
const { OggOpusDecoder } = require('ogg-opus-decoder');
const fs = require('fs');
const decoder = new OggOpusDecoder();
const input = fs.createReadStream('path/to/your/file.ogg');
const output = fs.createWriteStream('path/to/output/file.pcm');
input.pipe(decoder).pipe(output);
Streaming Decoded Audio
This feature allows you to stream decoded audio directly to a speaker. The code sample demonstrates how to read an Ogg Opus file, decode it, and stream the audio to a speaker for playback.
const { OggOpusDecoder } = require('ogg-opus-decoder');
const fs = require('fs');
const Speaker = require('speaker');
const decoder = new OggOpusDecoder();
const input = fs.createReadStream('path/to/your/file.ogg');
const speaker = new Speaker({
channels: 2, // 2 channels (stereo)
bitDepth: 16, // 16-bit samples
sampleRate: 48000 // 48,000 Hz sample rate
});
input.pipe(decoder).pipe(speaker);
node-opus is a Node.js native binding to libopus, which allows for encoding and decoding of Opus audio streams. Unlike ogg-opus-decoder, node-opus provides more low-level control over the encoding and decoding process, making it suitable for applications that need to handle Opus audio streams directly.
opusscript is a pure JavaScript implementation of the Opus codec. It can be used in both Node.js and browser environments. While it offers similar functionality to ogg-opus-decoder, it is not as performant as native bindings like node-opus or ogg-opus-decoder due to being implemented in JavaScript.
web-audio-api is a high-level API for processing and synthesizing audio in web applications. It provides a wide range of audio processing capabilities, including decoding audio files. While it is more general-purpose compared to ogg-opus-decoder, it can be used to achieve similar results for decoding and playing back audio.
ogg-opus-decoder
ogg-opus-decoder
is a Web Assembly Ogg Opus audio decoder.
libopus
and codec-parser
See the homepage of this repository for more Web Assembly audio decoders like this one.
Install from NPM.
Run npm i ogg-opus-decoder
import { OggOpusDecoder } from 'ogg-opus-decoder';
const decoder = new OggOpusDecoder();
Or download the build and include it as a script.
<script src="ogg-opus-decoder.min.js"></script>
<script>
const decoder = new window["ogg-opus-decoder"].OggOpusDecoder();
</script>
Create a new instance and wait for the WASM to finish compiling. Decoding can be done on the main thread synchronously, or in a webworker asynchronously.
Main thread synchronous decoding
import { OggOpusDecoder } from 'ogg-opus-decoder';
const decoder = new OggOpusDecoder();
// wait for the WASM to be compiled
await decoder.ready;
Web Worker asynchronous decoding
import { OggOpusDecoderWebWorker } from 'ogg-opus-decoder';
const decoder = new OggOpusDecoderWebWorker();
// wait for the WASM to be compiled
await decoder.ready;
Begin decoding Ogg Opus data.
// Decode an individual Opus frame
const {channelData, samplesDecoded, sampleRate} = decoder.decode(oggOpusData);
When done decoding, reset the decoder to decode a new stream, or free up the memory being used by the WASM module if you have no more audio to decode.
// `reset()` clears the decoder state and allows you do decode a new stream of Ogg Opus data.
await decoder.reset();
// `free()` de-allocates the memory used by the decoder. You will need to create a new instance after calling `free()` to start decoding again.
decoder.free();
Decoded audio is always returned in the below structure.
{
channelData: [
leftAudio, // Float32Array of PCM samples for the left channel
rightAudio, // Float32Array of PCM samples for the right channel
... // additional channels
],
samplesDecoded: 1234, // number of PCM samples that were decoded per channel
sampleRate: 48000, // sample rate of the decoded PCM
errors: [ // array containing descriptions for any decode errors
{
message: "libopus -4 OPUS_INVALID_PACKET: The compressed data passed is corrupted",
frameLength: 400, // length of the frame or data in bytes that encountered an error
frameNumber: 21, // position of error relative to total frames decoded
inputBytes: 4905, // position of error relative to total input bytes
outputSamples: 18888, // position of error relative to total output samples
}
]
}
Each Float32Array within channelData
can be used directly in the WebAudio API for playback.
Decoding will proceed through any errors. Any errors encountered may result in gaps in the decoded audio.
Each channel is assigned to a speaker location in a conventional surround arrangement. Specific locations depend on the number of channels, and are given below in order of the corresponding channel indices. This set of surround options and speaker location orderings is the same as those used by the Vorbis codec.
See: https://datatracker.ietf.org/doc/html/rfc7845.html#section-5.1.1.2
OggOpusDecoder
Class that decodes Ogg Opus data synchronously on the main thread.
const decoder = new OggOpusDecoder({ forceStereo: true });
forceStereo
optional, defaults to false
true
to force stereo output when decoding mono or multichannel Ogg Opus.sampleRate
optional, defaults to 48000
8000, 12000, 16000, 24000, or 48000
decoder.ready
async
decoder.decode(oggOpusData)
async
oggOpusData
Uint8Array containing Ogg Opus data.decoder.decodeFile(oggOpusData)
async
oggOpusData
Uint8Array containing Ogg Opus data.decoder.flush()
async
decode
method to retrieve any remaining data in the buffer.decoder.reset()
async
decoder.free()
free()
, the current instance is made unusable, and a new instance will need to be created to decode additional Ogg Opus data.OggOpusDecoderWebWorker
Class that decodes Ogg Opus data asynchronously within a web worker. Decoding is performed in a separate, non-blocking thread. Each new instance spawns a new worker allowing you to run multiple workers for concurrent decoding of multiple streams.
const decoder = new OggOpusDecoderWebWorker({ forceStereo: true });
forceStereo
optional, defaults to false
true
to force stereo output when decoding mono or multichannel Ogg Opus.sampleRate
optional, defaults to 48000
8000, 12000, 16000, 24000, or 48000
decoder.ready
async
decoder.decode(oggOpusData)
async
oggOpusData
Uint8Array containing Ogg Opus data.decoder.decodeFile(oggOpusData)
async
oggOpusData
Uint8Array containing Ogg Opus data.decoder.flush()
async
decode
method to retrieve any remaining data in the buffer.decoder.reset()
async
decoder.free()
async
free()
, the current instance is made unusable, and a new instance will need to be created to decode additional Ogg Opus data.OggOpusDecoderWebWorker
uses async functions to send operations to the web worker without blocking the main thread. To fully take advantage of the concurrency provided by web workers, your code should avoid using await
on decode operations where it will block the main thread.
Each method call on a OggOpusDecoderWebWorker
instance will queue up an operation to the web worker. Operations will complete within the web worker thread one at a time and in the same order in which the methods were called.
Good Main thread is not blocked during each decode operation. The example playAudio
function is called when each decode operation completes. Also, the next decode operation can begin while playAudio
is doing work on the main thread.
const playAudio = ({ channelData, samplesDecoded, sampleRate }) => {
// does something to play the audio data.
}
decoder.decode(data1).then(playAudio);
decoder.decode(data2).then(playAudio);
decoder.decode(data3).then(playAudio);
// do some other operations while the audio is decoded
Bad Main thread is being blocked by await
during each decode operation. Synchronous code is halted while decoding completes, negating the benefits of using a webworker.
const decoded1 = await decoder.decode(data1); // blocks the main thread
playAudio(decoded1);
const decoded2 = await decoder.decode(data2); // blocks the main thread
playAudio(decoded2);
const decoded3 = await decoder.decode(data3); // blocks the main thread
playAudio(decoded3);
OggOpusDecoderWebWorker
This example shows how to decode multiple files using a single OggOpusDecoderWebWorker
instance. This code iterates over an array of input files (Array of Uint8Arrays) and queues up each file to be decoded one at a time.
First, wait for the decoder to become ready by calling decoder.ready
.
For each iteration, decode()
is called, it's result is pushed to the decodedFiles
array, and decoder.reset()
is called to prepare the decoder for a new file. These operations are queued up to the decoder instance and will complete one after another.
Finally, a call to decoder.free()
is queued to clean up the memory stored by the decoder. This resolves when it and all of the other operations before it complete.
It's important to note that there is only one await
operations in this example. Decoding can happen asynchronously and you only need to await
when you need to use the results of the decode operation.
const inputFiles = [file1, file2, file3] // Array of Uint8Array file data
const decoder = new OggOpusDecoderWebWorker();
const decodedFiles = [];
const decodePromise = decoder.ready // wait for the decoder to be ready
.then(() => {
for (const file of inputFiles) {
decoder.decode(file) // queue the decode operation
.then((result) => decodedFiles.push(result)); // save the decode result after decode completes
decoder.reset(); // queue the reset operation
}
})
.then(() => decoder.free()); // queue the free operation that will execute after the above operations
// do sync operations here
// await when you need to have the all of the audio data decoded
await decodePromise;
OggOpusDecoderWebWorker
This example shows how to decode multiple files using multiple instances of OggOpusDecoderWebWorker
. This code iterates over an array of input files (Array of Uint8Arrays) and spawns a new OggOpusDecoderWebWorker
instance for each file and decodes the file. If you want to take full advantage of multi-core devices, this is the approach you will want to take since it will parallelize the decoding
For each input file, a new decoder is created, and the file is decoded using the decode()
after decoder.ready
is resolved. The result of the decode()
operation is returned, and a finally()
function on the promise calls decoder.free()
to free up the instance after the decode operations are completed.
Finally, Promise.all()
wraps this array of promises and resolves when all decode operations are complete.
It's important to note that there is only one await
operation in this example. Decoding can happen asynchronously and you only need to await
when you need to use the results of the decode operation.
const inputFiles = [file1, file2, file3] // Array of Uint8Array file data
// loops through each Uint8Array in `inputFiles` and decodes the files in separate threads
const decodePromise = Promise.all(
inputFiles.map((file) => {
const decoder = new OggOpusDecoderWebWorker();
return decoder.ready
.then(() => decoder.decode(file)) // decode the input file
.finally(() => decoder.free()); // free the decoder after resolving the decode result
})
);
// do sync operations here
// await when you need to have the all of the audio data decoded
const decodedFiles = await decodePromise;
FAQs
Web Assembly streaming Ogg Opus decoder
The npm package ogg-opus-decoder receives a total of 212,878 weekly downloads. As such, ogg-opus-decoder popularity was classified as popular.
We found that ogg-opus-decoder demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.