### Install libflac.js in Node.js Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html Install the library using npm, either from npm or directly from the GitHub repository. ```bash # install from npm npm install --save libflacjs ``` ```bash # install latest from master branch npm install --save git+https://github.com/mmig/libflac.js.git ``` -------------------------------- ### Build libflac.js Source: https://github.com/mmig/libflac.js/blob/master/README.md Start the build process for libflac.js by executing the Makefile. This assumes Emscripten is installed and configured, and the appropriate toolchain is activated. ```bash make ``` -------------------------------- ### Install libflac.js via npm Source: https://context7.com/mmig/libflac.js/llms.txt Install the libflac.js npm package to use it in your project. ```bash npm install --save libflacjs ``` -------------------------------- ### Configuration and State Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CueSheetTrack.html Functions for getting and setting options, and checking the library's ready state. ```APIDOC ## getOptions ### Description Retrieves the current options of the FLAC library. ### Method getOptions ### Parameters None explicitly documented. ### Response None explicitly documented. ``` ```APIDOC ## setOptions ### Description Sets options for the FLAC library. ### Method setOptions ### Parameters None explicitly documented. ### Response None explicitly documented. ``` ```APIDOC ## isReady ### Description Checks if the FLAC library is ready for use. ### Method isReady ### Parameters None explicitly documented. ### Response None explicitly documented. ``` -------------------------------- ### Configuration and State Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CoderChangedEventData.html Functions for getting and setting encoder/decoder options and checking readiness. ```APIDOC ## getOptions ### Description Retrieves the current options for the encoder or decoder. ### Method `getOptions(instance)` ### Parameters - `instance` (object) - The encoder or decoder instance. ### Response Returns an object containing the current options. ``` ```APIDOC ## setOptions ### Description Sets options for the encoder or decoder. ### Method `setOptions(instance, options)` ### Parameters - `instance` (object) - The encoder or decoder instance. - `options` (object) - An object containing the options to set. ### Response Returns true on success, false on failure. ``` ```APIDOC ## isReady ### Description Checks if the encoder or decoder is ready. ### Method `isReady(instance)` ### Parameters - `instance` (object) - The encoder or decoder instance. ### Response Returns true if ready, false otherwise. ``` -------------------------------- ### Configuration and State Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__EntropyCodingMethodType.html Functions for getting and setting options, and checking the ready state of the library. ```APIDOC ## getOptions ### Description Retrieves the current options of the FLAC library. ### Method Not specified (likely a function call in a JS API) ### Endpoint Not applicable (SDK function) ### Parameters None explicitly documented. ### Request Example ```javascript // Example usage (details not provided in source) const options = getOptions(); ``` ### Response None explicitly documented. ``` ```APIDOC ## setOptions ### Description Sets options for the FLAC library. ### Method Not specified (likely a function call in a JS API) ### Endpoint Not applicable (SDK function) ### Parameters None explicitly documented. ### Request Example ```javascript // Example usage (details not provided in source) setOptions({ option1: 'value1' }); ``` ### Response None explicitly documented. ``` ```APIDOC ## isReady ### Description Checks if the FLAC library is ready for use. ### Method Not specified (likely a function call in a JS API) ### Endpoint Not applicable (SDK function) ### Parameters None explicitly documented. ### Request Example ```javascript // Example usage (details not provided in source) if (isReady()) { // Library is ready } ``` ### Response None explicitly documented. ``` -------------------------------- ### Configuration and State Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__StreamDecoderState.html Functions for getting and setting encoder/decoder options, and checking readiness. ```APIDOC ## getOptions ### Description Retrieves the current options for the FLAC instance. ### Method `getOptions()` ## setOptions ### Description Sets options for the FLAC instance. ### Method `setOptions(options)` ### Parameters - `options` (object) - An object containing the options to set. ## isReady ### Description Checks if the FLAC instance is ready. ### Method `isReady()` ### Returns - `boolean` - True if ready, false otherwise. ``` -------------------------------- ### Configuration and State Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.SeekPoint.html Functions for getting, setting options, and checking the ready state of the FLAC library. ```APIDOC ## getOptions ### Description Retrieves the current options for the FLAC library. ### Method Not specified (assumed to be a function call) ### Parameters None explicitly documented. ### Response None explicitly documented. ``` ```APIDOC ## setOptions ### Description Sets options for the FLAC library. ### Method Not specified (assumed to be a function call) ### Parameters None explicitly documented. ### Response None explicitly documented. ``` ```APIDOC ## isReady ### Description Checks if the FLAC library is ready for use. ### Method Not specified (assumed to be a function call) ### Parameters None explicitly documented. ### Response None explicitly documented. ``` -------------------------------- ### Decode FLAC to PCM with libflac.js Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html This example demonstrates how to initialize and use the Decoder class from libflac.js for decoding FLAC audio data. It covers both single-chunk and streaming (chunked) decoding modes, and how to retrieve the decoded PCM samples and metadata. Ensure you have the necessary FLAC data and have imported the library correctly. ```javascript const Flac = require('libflacjs')(); //or as import (see section "Including libflac.js" for more details): // import * as flacFactory from 'libflacjs'; // const Flac = flacFactory(); const Decoder = require('libflacjs/lib/decoder').Decoder; //or as import: //import { Decoder } from 'libflacjs/lib/decoder'; //NOTE if async-library variant is used, should wait for initialization: //Flac.onready(function(){ ... const binData = new Uint8Array(someFlacData);// <- someFlacData: binary FLAC data const decodingMode = 'single';// "single" | "chunked" const decoder = new Decoder(Flac, { verify: true // boolean (OPTIONAL) isOgg: false // boolean (OPTIONAL), if FLAC audio is wrapped in OGG container }); if(decodingMode === 'single'){ //use as-single-chunk mode: invokce decode once with the complete FLAC data decoder.decode(binData); } else { //use multiple-chunks mode ("streaming"): invoke decodeChunk(...) for each chunk... decoder.decodeChunk(binData); //... and finalize decoding by invoking decodeChunk() without arguments decoder.decodeChunk(); } const decData = decoder.getSamples(/* return interleaved samples? */ true);// <- returns Uint8Array //or: non-interleaved samples, i.e. array of channels data: // const decData = decoder.getSamples(false);// <- returns Uint8Array[] const metadata = decoder.metadata; decoder.destroy(); // or decoder.reset() for reusing the decoder instance // -> do something with the decoded PCM audio data decData and metadata ``` -------------------------------- ### Options Management Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__ChannelAssignment.html Functions for getting and setting options for the FLAC library. ```APIDOC ## getOptions ### Description Retrieves the current options of the FLAC library. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable for SDK functions) ### Parameters (Not specified) ### Request Example (Not applicable for SDK functions) ### Response (Not specified) ## setOptions ### Description Sets options for the FLAC library. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable for SDK functions) ### Parameters (Not specified) ### Request Example (Not applicable for SDK functions) ### Response (Not specified) ``` -------------------------------- ### Build libflac.js from Source Source: https://context7.com/mmig/libflac.js/llms.txt Compile the Emscripten-based libflac.js library from the libFLAC C source using the provided Makefile. Ensure Emscripten SDK is installed and activated. ```bash # Install and activate Emscripten (LLVM toolchain, v1.39.x or later) emsdk list emsdk install 1.39.19 emsdk activate 1.39.19 # sets up PATH and environment # Alternatively source the env script printed by emsdk activate source /path/to/emsdk/emsdk_env.sh # Build all library variants (downloads libFLAC and libogg automatically) make # To change the targeted libFLAC version, edit the Makefile: # FLAC_VERSION:=1.3.3 ``` -------------------------------- ### Async Initialization with Event Listener Source: https://context7.com/mmig/libflac.js/llms.txt Use an event listener to ensure the library is ready before use, especially for variants that load binary files asynchronously. ```javascript const FlacFactory = require('libflacjs'); const Flac = FlacFactory('min.wasm'); // Approach 1: event listener Flac.on('ready', function(event) { const libFlac = event.target; // same as Flac startProcessing(libFlac); }); function startProcessing(flac) { console.log('libflac.js is ready, variant:', flac.variant); // e.g. "release.wasm" } ``` -------------------------------- ### Building from Source Source: https://context7.com/mmig/libflac.js/llms.txt Instructions for building the Emscripten-compiled library from the libFLAC C source using the provided Makefile. ```APIDOC ## Building from source Build the Emscripten-compiled library from the libFLAC C source using the provided Makefile. ```bash # Install and activate Emscripten (LLVM toolchain, v1.39.x or later) emsdk list emsdk install 1.39.19 emsdk activate 1.39.19 # sets up PATH and environment # Alternatively source the env script printed by emsdk activate source /path/to/emsdk/emsdk_env.sh # Build all library variants (downloads libFLAC and libogg automatically) make # To change the targeted libFLAC version, edit the Makefile: # FLAC_VERSION:=1.3.3 ``` ``` -------------------------------- ### Install libflac.js with npm Source: https://github.com/mmig/libflac.js/blob/master/README.md Install libflac.js from npm for use in Node.js projects. You can install the latest stable version or the latest from the master branch. ```bash # install from npm npm install --save libflacjs # install latest from master branch npm install --save git+https://github.com/mmig/libflac.js.git ``` -------------------------------- ### Install file-loader for webpack Source: https://github.com/mmig/libflac.js/blob/master/README.md Install the file-loader npm package as a development dependency for webpack. ```bash npm install --save-dev file-loader ``` -------------------------------- ### Initialize libflac.js Decoder Source: https://github.com/mmig/libflac.js/blob/master/README.md Sets up the decoder configuration and creates a decoder instance. Ensure libflac.js is loaded and available. ```javascript //prerequisite: loaded libflac.js & available via variable Flac //NOTE if async-library variant is used, should wait for initialization: //Flac.onready(function(){ ... var VERIFY = true, USE_OGG = false; //////// // [1] CREATE -> IN: config { ... } (decoding parameters) //overwrite default configuration from config object VERIFY = config.isVerify;//verification can be disabled for speeding up decoding process //decode from native FLAC container or from OGG container USE_OGG = config.isOgg; // create decoder var flac_decoder = Flac.create_libflac_decoder(VERIFY); if (flac_decoder == 0){ return; } ``` -------------------------------- ### Initialization and State Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.LPCSubFrameData.html Functions for initializing the library and checking its readiness. ```APIDOC ## init_libflac_decoder ### Description Initializes the libflac decoder. ### Method Not applicable (function call) ## init_libflac_encoder ### Description Initializes the libflac encoder. ### Method Not applicable (function call) ## isReady ### Description Checks if the library is ready. ### Method Not applicable (function call) ### Returns - **boolean**: True if ready, false otherwise. ``` -------------------------------- ### Option Management Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.LPCSubFrameData.html Functions for getting and setting library options. ```APIDOC ## getOptions ### Description Retrieves the current library options. ### Method Not applicable (function call) ## setOptions ### Description Sets the library options. ### Method Not applicable (function call) ### Parameters - **options** (object) - Required - An object containing the options to set. ``` -------------------------------- ### Initialize FLAC Encoder Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html Sets up the FLAC encoder with specified audio parameters. Ensure libflac.js is loaded and available via the 'Flac' variable. If using the async variant, wait for initialization. ```javascript //prerequisite: loaded libflac.js & available via variable Flac //NOTE if async-library variant is used, should wait for initialization: //Flac.onready(function(){ ... var flac_encoder, CHANNELS = 1, SAMPLERATE = 44100, COMPRESSION = 5, BPS = 16, VERIFY = false, BLOCK_SIZE = 0, flac_ok = 1, USE_OGG = false; //////// // [1] CREATE -> IN param: config { ... } (encoding parameters) //overwrite default configuration from config object COMPRESSION = config.compression; BPS = config.bps; SAMPLERATE = config.samplerate; CHANNELS = config.channels; VERIFY = config.isVerify;//verification can be disabled for speeding up encoding process BLOCK_SIZE = config.blockSize; USE_OGG = config.useOgg; //init encoder flac_encoder = Flac.create_libflac_encoder(SAMPLERATE, CHANNELS, BPS, COMPRESSION, 0, VERIFY, BLOCK_SIZE); if (flac_encoder == 0){ return; } ``` -------------------------------- ### onready Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.BlockMetadata.html Callback function executed when the FLAC library is ready. ```APIDOC ## onready ### Description Callback function executed when the FLAC library is ready. ### Method [Method signature or relevant details if available] ### Parameters [Parameters if documented] ### Request Example [Example if available] ### Response [Response details if available] ``` -------------------------------- ### Async Initialization with onready Handler Source: https://context7.com/mmig/libflac.js/llms.txt Use the `onready` handler and `isReady()` guard for asynchronous initialization. This approach ensures the library is ready or sets up a callback for when it becomes ready. ```javascript const FlacFactory = require('libflacjs'); const Flac = FlacFactory('min.wasm'); // Approach 2: onready handler with isReady() guard if (!Flac.isReady()) { Flac.onready = function(event) { startProcessing(event.target); }; } else { // Library was already initialized synchronously startProcessing(Flac); } function startProcessing(flac) { console.log('libflac.js is ready, variant:', flac.variant); // e.g. "release.wasm" } ``` -------------------------------- ### isReady Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CodingOptions.html Checks if the FLAC instance is ready. ```APIDOC ## isReady ### Description Checks if the FLAC instance is ready. ### Method Not specified (likely a function call within the library) ### Parameters Not specified in the provided text. ### Request Example Not specified. ### Response Not specified. ``` -------------------------------- ### Handle libflac.js Ready Event Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html Use Flac.on('ready', ...) or Flac.onready to ensure libflac.js is fully initialized before use. This is crucial for variants that load binary files asynchronously. ```javascript Flac.on('ready', function(event){ var libFlac = event.target; //NOTE: Flac === libFlac //execute code that uses libflac.js: someFunctionForProcessingFLAC(); }); //... or set handler Flac.onready = function(event){ var libFlac = event.target; //NOTE: Flac === libFlac //execute code that uses libflac.js: someFunctionForProcessingFLAC(); }; ``` -------------------------------- ### General Utility Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CompletedReadResult.html Utility functions for initializing the library, checking readiness, and managing options. ```APIDOC ## init_libflac_encoder ### Description Initializes the libflac encoder. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ## init_libflac_decoder ### Description Initializes the libflac decoder. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ## isReady ### Description Checks if the libflac library is ready. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ## getOptions ### Description Retrieves the current options of the libflac instance. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ## setOptions ### Description Sets options for the libflac instance. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` -------------------------------- ### Load libflac.js variants in Node.js Source: https://github.com/mmig/libflac.js/blob/master/README.md Use the factory method to load default or optimized variants of libflac.js. Variants can be combined, for example, 'min.wasm'. ```javascript //load default/release asm.js variant: var Flac = require('libflacjs')(); // use one of the optimization-variants: // * / "release" // * "min" // * "dev" // use one of the technology-variants: // * / "asmjs" // * "wasm" // // can be combined with dot, e.g. "min.wasm": var FlacFactory = require('libflacjs'); var Flac = FlacFactory('min.wasm'); Flac.on('ready', function(event){ ... ``` -------------------------------- ### Initialize libflac.js Encoder Source: https://github.com/mmig/libflac.js/blob/master/README.md Sets up the FLAC encoder with specified audio parameters. Ensure libflac.js is loaded and available. For the async variant, wait for initialization. ```javascript //prerequisite: loaded libflac.js & available via variable Flac //NOTE if async-library variant is used, should wait for initialization: //Flac.onready(function(){ ... var flac_encoder, CHANNELS = 1, SAMPLERATE = 44100, COMPRESSION = 5, BPS = 16, VERIFY = false, BLOCK_SIZE = 0, flac_ok = 1, USE_OGG = false; //////// // [1] CREATE -> IN param: config { ... } (encoding parameters) //overwrite default configuration from config object COMPRESSION = config.compression; BPS = config.bps; SAMPLERATE = config.samplerate; CHANNELS = config.channels; VERIFY = config.isVerify;//verification can be disabled for speeding up encoding process BLOCK_SIZE = config.blockSize; USE_OGG = config.useOgg; //init encoder flac_encoder = Flac.create_libflac_encoder(SAMPLERATE, CHANNELS, BPS, COMPRESSION, 0, VERIFY, BLOCK_SIZE); if (flac_encoder == 0){ return; } //////// // [2] INIT -> OUT: encBuffer (encoded data), metaData (OPTIONALLY, FLAC metadata) //for storing the encoded FLAC data var encBuffer = []; //for storing the encoding FLAC metadata summary var metaData; // [2] (a) setup writing (encoded) output data var write_callback_fn = function(encodedData /*Uint8Array*/, bytes, samples, current_frame){ //store all encoded data "pieces" into a buffer encBuffer.push(encodedData); }; // [2] (b) optional callback for receiving metadata function metadata_callback_fn(data){ // data -> [example] { // min_blocksize: 4096, // max_blocksize: 4096, // min_framesize: 14, // max_framesize: 5408, // sampleRate: 44100, // channels: 2, // bitsPerSample: 16, // total_samples: 267776, // md5sum: "50d4d469448e5ea75eb44ab6b7f111f4" //} console.info('meta data: ', data); metaData = data; } // [2] (c) initialize to either write to native-FALC or to OGG container var status_encoder; if(!USE_OGG){ // encode to native FLAC container status_encoder = Flac.init_encoder_stream(flac_encoder, write_callback_fn, //required callback(s) metadata_callback_fn //optional callback(s) ); } else { // encode to OGG container status_encoder = Flac.init_encoder_ogg_stream(flac_encoder, write_callback_fn, //required callback(s) metadata_callback_fn //optional callback(s) ); } flac_ok &= (status_encoder == 0); ``` -------------------------------- ### Encoder Initialization and Control Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CueSheetTrack.html Functions for creating, finishing, and deleting FLAC stream encoders, along with methods to get encoder state and verify settings. ```APIDOC ## create_libflac_encoder ### Description Creates a new libFLAC stream encoder instance. ### Method (Implicitly a constructor or factory function) ### Endpoint N/A (JavaScript function) ### Parameters None explicitly documented. ### Request Example ```javascript const encoder = Flac.create_libflac_encoder(); ``` ### Response - Returns an encoder instance. ## FLAC__stream_encoder_delete ### Description Deletes a libFLAC stream encoder instance, freeing associated resources. ### Method (Implicitly a cleanup function) ### Endpoint N/A (JavaScript function) ### Parameters - `encoder` (object) - The encoder instance to delete. ### Request Example ```javascript Flac.FLAC__stream_encoder_delete(encoder); ``` ### Response None explicitly documented. ## FLAC__stream_encoder_finish ### Description Finishes the encoding process and flushes any buffered data. ### Method (Implicitly a finalization function) ### Endpoint N/A (JavaScript function) ### Parameters - `encoder` (object) - The encoder instance. ### Request Example ```javascript Flac.FLAC__stream_encoder_finish(encoder); ``` ### Response None explicitly documented. ## FLAC__stream_encoder_get_state ### Description Retrieves the current state of the libFLAC stream encoder. ### Method (Implicitly a getter function) ### Endpoint N/A (JavaScript function) ### Parameters - `encoder` (object) - The encoder instance. ### Request Example ```javascript const state = Flac.FLAC__stream_encoder_get_state(encoder); ``` ### Response - Returns the encoder state. ## FLAC__stream_encoder_get_verify ### Description Retrieves the current verify setting of the libFLAC stream encoder. ### Method (Implicitly a getter function) ### Endpoint N/A (JavaScript function) ### Parameters - `encoder` (object) - The encoder instance. ### Request Example ```javascript const verifyStatus = Flac.FLAC__stream_encoder_get_verify(encoder); ``` ### Response - Returns the verify status (likely a boolean or status code). ## FLAC__stream_encoder_get_verify_decoder_state ### Description Retrieves the state of the verify decoder used by the libFLAC stream encoder. ### Method (Implicitly a getter function) ### Endpoint N/A (JavaScript function) ### Parameters - `encoder` (object) - The encoder instance. ### Request Example ```javascript const verifyDecoderState = Flac.FLAC__stream_encoder_get_verify_decoder_state(encoder); ``` ### Response - Returns the state of the verify decoder. ``` -------------------------------- ### Handle libflac.js Async Initialization with Flac.on() Source: https://github.com/mmig/libflac.js/blob/master/README.md Use Flac.on('ready', ...) to execute code after libflac.js has been fully initialized. This is the recommended approach for handling asynchronous loading. ```javascript Flac.on('ready', function(event){ var libFlac = event.target; //NOTE: Flac === libFlac //execute code that uses libflac.js: someFunctionForProcessingFLAC(); }; ``` -------------------------------- ### Load libflac.js in a WebWorker script Source: https://github.com/mmig/libflac.js/blob/master/README.md Load `libflac.js` within a WebWorker script. This example shows how to include single-file variants or WASM variants, ensuring binary files are included by webpack. ```javascript //importScripts('libflac.js');//<- normal way to load a script within a WebWorker // for including a "single file variant" of libflac.js, e.g. the standard version: var Flac = require('libflacjs/dist/libflac.js'); // OR for including a .wasm variant, e.g standard-wasm (for binary of min-version include its *.mem file): require.resolve('libflacjs/dist/libflac.wasm.wasm') // <- force webpack to include the binary file var Flac = require('libflacjs/dist/libflac.wasm.js') self.onmessage = function(event) { console.log('received message from main thread ', event.data); } ``` -------------------------------- ### on Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.html Adds an event listener for module-level events, such as 'ready', 'created', and 'destroyed'. ```APIDOC ## on(eventName, listener) ### Description Add an event listener for module-events. Supported events: * `"ready"` → [`Flac.event:ReadyEvent`](Flac.html#.event:ReadyEvent): emitted when module is ready for usage (i.e. [`isReady`](Flac.html#isReady) is true) _NOTE listener will get immediately triggered if module is already `"ready"`_ * `"created"` → [`Flac.event:CreatedEvent`](Flac.html#.event:CreatedEvent): emitted when an encoder or decoder instance was created * `"destroyed"` → [`Flac.event:DestroyedEvent`](Flac.html#.event:DestroyedEvent): emitted when an encoder or decoder instance was destroyed ### Parameters #### Path Parameters - **eventName** (string) - **listener** (function) ### Example Flac.on('ready', function(event){ //gets executed when library is ready, or becomes ready... }); ``` -------------------------------- ### Dynamic Function Invocation Example Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html Demonstrates how to handle dynamically invoked functions when using the exported-functions script. Add a DEV comment where the function is explicitly stated as a string if it might be invoked dynamically. ```javascript //DEV comment for exported-functions script: // Module.ccall('FLAC__stream_decoder_init_stream' // Module.ccall('FLAC__stream_decoder_init_ogg_stream' var func_name = test? 'FLAC__stream_decoder_init_stream' : 'FLAC__stream_decoder_init_ogg_stream'; Module.ccall( func_name, ``` -------------------------------- ### onready Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CueSheetTracIndex.html An event that fires when the FLAC library is ready. ```APIDOC ## onready Event ### Description This event is emitted when the libFLAC.js library has completed its initialization and is ready for use. It's a convenient way to know when you can start encoding or decoding. ### Method Event listener registration (typically via `on('ready', callback)`) ### Endpoint Not applicable (SDK event) ### Parameters * `callback` (function) - The function to execute when the 'ready' event is fired. ### Request Example ```javascript // Example usage // on('ready', () => { // console.log('FLAC library is now ready to use!'); // }); ``` ### Response * The callback function is executed. ``` -------------------------------- ### Decode FLAC Metadata with libflac.js Source: https://github.com/mmig/libflac.js/blob/master/README.md Example for extracting metadata when decoding FLAC audio. Prerequisites include a loaded and initialized Flac library and a created decoder instance. Metadata types can be enabled individually or all at once. ```javascript // prerequisites: loaded & initialized Flac library //... create decoder flacDecoder (see code examples above) //enable all metadata types: Flac.FLAC__stream_decoder_set_metadata_respond_all(flacDecoder); //or enable only seek table metadata: Flac.FLAC__stream_decoder_set_metadata_respond(flacDecoder, 3); // example seek table metadata (see docs for details): // { // num_points: 1, // points: [{ // frame_samples: 4096, // sample_number: 0, // stream_offset: 0 // }] // } //or enable only vorbis comment metadata: Flac.FLAC__stream_decoder_set_metadata_respond(flacDecoder, 4); // example vorbis comment metadata: // { // vendor_string: "reference libFLAC 1.3.3 20190804", // num_comments: 1, // comments: ["TRACKNUMBER=2/9"] // } //or enable only cue sheet metadata: Flac.FLAC__stream_decoder_set_metadata_respond(flacDecoder, 5); // example cue sheet metadata (see docs for details): // { // is_cd: 0, // lead_in: 88200, // media_catalog_number: "1234567890123", // num_tracks: 2, // tracks: [{ // isrc: "", // num_indices: 1, // indices: [{offset: 0, number: 1}], // number: 1, // offset: 0, // pre_emphasis: false, // type: "AUDIO" // }, { // isrc: "", // num_indices: 0, // indices: [], // number: 170, // offset: 267776, // pre_emphasis: false, // type: "AUDIO" // }] // } //or enable only all picture metadata: Flac.FLAC__stream_decoder_set_metadata_respond(flacDecoder, 6); // example picture metadata: // { // type: 3, // image type (see docs FLAC__StreamMetadata_Picture_Type) // mime_type: "image/jpeg", //the mime type // description: "Cover image for the track", // width: 1144, // the image width in pixel // height: 1144, // the image height in pixel // depth: 24, // the depth in bits // colors: 0, // colors (e.g. for GIF images) // data_length: 45496, // the size of the binary image data (in bytes) // data: Uint8Array // the binary image data // } //the metadata callback which stores the metadata in a list: var streamMetadata, metadataList = []; function metadata_callback_fn(data, dataBlock){ if(data){ // the stream metadata: streamMetadata = data; } else { // other metadata types: metadataList.push(dataBlock); // dataBlock[example]: // { // data: METADATA, // the metadata, e.g. stream info, seek table, vorbis comment, picture,... // isLast: 0, // wether the metadata block is the last block befor the audio data // length: 1032, // the length/size of the metadata (in byte) // type: 4, // metadata type, [0, 6] (higher metadata types are as of yet UNKNOWN) // } } } //... initilize decoder flacDecoder with metadata_callback_fn, // and decode flac data (see code examples above) ``` -------------------------------- ### onready Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__MetadataType.html Registers a callback function to be executed when the FLAC object is ready. ```APIDOC ## onready ### Description Registers a callback function to be executed when the FLAC object is ready. ### Method Not specified (likely a function call in a library) ### Parameters - **callback** (function) - Required - The function to execute when the object is ready. ### Return Value - (object) - The FLAC object for chaining. ``` -------------------------------- ### onready Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.ApplicationMetadata.html Registers a callback function to be executed when the FLAC object is ready. ```APIDOC ## onready ### Description Registers a callback function to be executed when the FLAC object is ready. ### Method Not specified (likely a function call in a library) ### Parameters - **callback** (function) - Required - The function to execute when the object is ready. ``` -------------------------------- ### Setup Callbacks for libflac.js Decoding Source: https://github.com/mmig/libflac.js/blob/master/README.md Defines callback functions for reading input FLAC data, writing decoded audio data, and handling errors or metadata. The read callback should return -1 for end-of-stream. ```javascript //////// // [2] INIT -> OUT: decBuffer (decoded data), metaData (OPTIONALLY, FLAC metadata) // IN: flacData Uint8Array (FLAC data) // [2] (a) setup reading input data var currentDataOffset = 0; var size = flacData.buffer.byteLength; //function that will be called for reading the input (FLAC) data: function read_callback_fn(bufferSize){ var end = currentDataOffset === size? -1 : Math.min(currentDataOffset + bufferSize, size); var _buffer; var numberOfReadBytes; if(end !== -1){ _buffer = flacData.subarray(currentDataOffset, end); numberOfReadBytes = end - currentDataOffset; currentDataOffset = end; } else { //nothing left to read: return zero read bytes (indicates end-of-stream) numberOfReadBytes = 0; } return {buffer: _buffer, readDataLength: numberOfReadBytes, error: false}; } // [2] (b) setup writing (decoded) output data //for "buffering" the decoded data: var decBuffer = []; //for storing the decoded FLAC metadata var metaData; //function that will be called for decoded output data (WAV audio) function write_callback_fn(channelsBuffer, frameHeader){ // channelsBuffer is an Array of the decoded audio data (Uint8Array): // the length of array corresponds to the channels, i.e. there is an Uint8Array for each channel // frameHeader -> [example] { // bitsPerSample: 8 // blocksize: 4096 // channelAssignment: 0 // channels: 2 // crc: 0 // number: 204800 // numberType: "samples" // sampleRate: 44100 // subframes: undefined // -> needs to be enabled via // // Flac.setOptions(flac_decoder, {analyseSubframes: true}) // // -> see API documentation //} decBuffer.push(channelsBuffer); } // [2] (c) optional callbacks for receiving details about errors and/or metadata function error_callback_fn(err, errMsg, client_data){ console.error('decode error callback', err, errMsg); } function metadata_callback_fn(data){ // data -> [example] { // min_blocksize: 4096, // max_blocksize: 4096, // min_framesize: 14, // max_framesize: 5408, // sampleRate: 44100, // channels: 2, // bitsPerSample: 16, // total_samples: 267776, // md5sum: "50d4d469448e5ea75eb44ab6b7f111f4" //} console.info('meta data: ', data); metaData = data; } // [2] (d) intialize for reading from native-FLAC or from OGG container var flac_ok = 1; var status_decoder; if(!USE_OGG){ // decode from native FLAC container status_decoder = Flac.init_decoder_stream( flac_decoder, read_callback_fn, write_callback_fn, //required callback(s) error_callback_fn, metadata_callback_fn //optional callback(s) ); } else { // decode from OGG container status_decoder = Flac.init_decoder_ogg_stream( flac_decoder, read_callback_fn, write_callback_fn, //required callback(s) error_callback_fn, metadata_callback_fn //optional callback(s) ); } flac_ok &= status_decoder == 0; if(flac_ok != 1){ return; } ``` -------------------------------- ### on Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.PictureMetadata.html Adds an event listener to the FLAC instance. ```APIDOC ## on ### Description Adds an event listener to the FLAC instance. ### Method on ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided in the source) ### Response (No specific response details documented in the source) ``` -------------------------------- ### Encoding Audio Data with libflac.js Encoder Source: https://github.com/mmig/libflac.js/blob/master/README.md Example demonstrating how to use the `Encoder` utility class to encode PCM audio data into FLAC format. This snippet covers both interleaved and channel-based audio data, streaming, finalizing encoding, retrieving encoded data, and exporting the FLAC file. Ensure the `Flac` library is initialized, especially if using the async variant. ```javascript const Flac = require('libflacjs')(); //or as import (see section "Including libflac.js" for more details): // import * as flacFactory from 'libflacjs'; // const Flac = flacFactory(); const Encoder = require('libflacjs/lib/encoder').Encoder; //or as import: //import { Encoder } from 'libflacjs/lib/encoder'; //helper function for converting interleaved audio to list of channel-audio arrays //(for actual code, see example in tools/test/util/utils-enc.ts): // function deinterleave(Int32Array, channels) => Int32Array[] //NOTE if async-library variant is used, should wait for initialization: //Flac.onready(function(){ ... const data = new Int32Array(someAudioData);//<- someAudioData: PCM audio data converted to Int32Array samples const encodingMode = 'interleaved';// "interleaved" | "channels" const encoder = new Encoder(Flac, { sampleRate: sampleRate, // number, e.g. 44100 channels: channels, // number, e.g. 1 (mono), 2 (stereo), ... bitsPerSample: bitsPerSample, // number, e.g. 8 or 16 or 24 compression: compressionLevel, // number, value between [0, 8] from low to high compression verify: true, // boolean (OPTIONAL) isOgg: false // boolean (OPTIONAL), if encoded FLAC should be wrapped in OGG container }); if(encodingMode === 'interleaved'){ //encode interleaved audio data (call multiple times for multiple audio chunks, i.e. "streaming") encoder.encode(data); //NOTE if data is TypedArray other than Int32Array then optional argument numberOfSamples MUST be given: //encoder.encode(data, numberOfSamples); } else { //if necessary, de-interleave data into channels-array // i.e. a list/array of Int32Arrays, one for each channel (list.length corresponds to channels); see comments about function deinterleave above const list = deinterleave(data, channels);// should return an list of Int32Arrays which's length corresponds to the number of channels //do encode to FLAC (call multiple times for multiple audio chunks, i.e. "streaming") encoder.encode(list); //NOTE if data was TypedArray other than Int32Array then optional argument numberOfSamples MUST be given: //encoder.encode(list, numberOfSamples); } encoder.encode();//<- finalize encoding by invoking encode() without arguments //get the encoded data: const encData = encoder.getSamples(); const metadata = encoder.metadata; encoder.destroy(); // or encoder.reset() for reusing the encoder instance // -> do something with the encoded FLAC data encData and metadata // e.g. update header with final metadata & create FLAC file Blob: const exportFlacFile = require('libflacjs/lib/utils').exportFlacFile; const flacBlob = exportFlacFile(encData, metadata, /* if encode in OGG container: */ false); ``` -------------------------------- ### on Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CueSheetTracIndex.html Attaches an event listener to the FLAC object. ```APIDOC ## on ### Description Attaches an event listener function to be called when a specific event is emitted by the FLAC object. ### Method Not specified (likely a function call in a JS SDK) ### Endpoint Not applicable (SDK function) ### Parameters * `event` (string) - The name of the event to listen for (e.g., 'ready', 'created', 'destroyed'). * `listener` (function) - The callback function to execute when the event is triggered. ### Request Example ```javascript // Example usage // on('ready', () => { // console.log('FLAC encoder/decoder is ready.'); // }); ``` ### Response None. ``` -------------------------------- ### getOptions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__MetadataType.html Retrieves the current options of the FLAC encoder or decoder. ```APIDOC ## getOptions ### Description Retrieves the current options of the FLAC encoder or decoder. ### Method Not specified (likely a function call in a library) ### Return Value - (object) - An object containing the current options. ``` -------------------------------- ### getOptions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.ApplicationMetadata.html Retrieves the current options of the FLAC encoder or decoder. ```APIDOC ## getOptions ### Description Retrieves the current options of the FLAC encoder or decoder. ### Method Not specified (likely a function call in a library) ### Response - **options** (object) - An object containing the current configuration options. ``` -------------------------------- ### List Emscripten SDK Versions Source: https://github.com/mmig/libflac.js/blob/master/doc/index.html Lists available Emscripten SDK versions. Use this to determine which version to activate. ```bash emsdk list ``` -------------------------------- ### onready Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FixedSubFrameData.html Registers a callback function to be executed when the FLAC encoder or decoder is ready. ```APIDOC ## onready ### Description Registers a callback function to be executed when the FLAC encoder or decoder is ready. ### Method Not applicable (function call) ### Parameters (Details not provided in source) ### Request Example (Not applicable) ### Response (Details not provided in source) ``` -------------------------------- ### Handle libflac.js Async Initialization with Flac.onready Source: https://github.com/mmig/libflac.js/blob/master/README.md Alternatively, assign a handler function to Flac.onready to execute code once libflac.js is initialized. Ensure Object.defineProperty is supported or check Flac.isReady() if initializing after the library is already ready. ```javascript Flac.onready = function(event){ var libFlac = event.target; //NOTE: Flac === libFlac //execute code that uses libflac.js: someFunctionForProcessingFLAC(); }; ``` -------------------------------- ### Utility Functions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__StreamDecoderErrorStatus.html Utility functions for checking readiness and managing options. ```APIDOC ## getOptions ### Description Retrieves the current options for the FLAC library. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` ```APIDOC ## isReady ### Description Checks if the FLAC library is ready for operations. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` ```APIDOC ## setOptions ### Description Sets options for the FLAC library. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` -------------------------------- ### Specify WAV Input Directory Source: https://github.com/mmig/libflac.js/blob/master/tools/test/README.md Place at least one WAV file in this directory. The recommended format is 96 kHz sampling rate and 24-bit encoding. ```bash /data/wav_src_files/*.wav ``` -------------------------------- ### Check libflac.js Ready State and Execute Code Source: https://github.com/mmig/libflac.js/blob/master/README.md If Object.defineProperty is not supported, check Flac.isReady() before setting the onready handler. If the library is already ready, execute the code immediately. ```javascript if( !Flac.isReady() ){ Flac.onready = function(event){ var libFlac = event.target; //NOTE: Flac === libFlac //call function that uses libflac.js: someFunctionForProcessingFLAC(); }; } else { //execute code that uses libflac.js: someFunctionForProcessingFLAC(); } ``` -------------------------------- ### getOptions Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.CodingOptions.html Retrieves the current coding options. ```APIDOC ## getOptions ### Description Retrieves the current coding options. ### Method Not specified (likely a function call within the library) ### Parameters Not specified in the provided text. ### Request Example Not specified. ### Response Not specified. ``` -------------------------------- ### Generate Audio Test Files Source: https://github.com/mmig/libflac.js/blob/master/tools/test/README.md Run this command to generate WAV files with different bit encodings (8, 16, 24) and sampling rates (8, 16, 20, 22.5, 32, 44.1, 48, 96 kHz). This creates 24 test files for each source WAV file. ```bash npm run gen:audio ``` -------------------------------- ### on Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.SeekTableMetadata.html Attaches an event listener. ```APIDOC ## on ### Description Attaches an event listener function to be called when a specific event is emitted by the FLAC instance. ### Method (Not specified, likely a function call in a JS SDK) ### Endpoint (Not applicable for SDK functions) ### Parameters (Parameters not detailed in the source) ### Request Example (Not applicable for SDK functions) ### Response (Response details not detailed in the source) ``` -------------------------------- ### init_libflac_decoder Source: https://github.com/mmig/libflac.js/blob/master/doc/Flac.FLAC__MetadataType.html Initializes the libFLAC decoder. ```APIDOC ## init_libflac_decoder ### Description Initializes the libFLAC decoder. ### Method Not specified (likely a function call in a library) ### Return Value - (boolean) - True if initialization was successful, false otherwise. ```