### Install @elemaudio/core Source: https://github.com/elemaudio/elementary/blob/main/js/packages/core/README.md Install the @elemaudio/core package using npm. ```bash npm install --save @elemaudio/core ``` -------------------------------- ### Install @elemaudio/web-renderer Source: https://github.com/elemaudio/elementary/blob/main/js/packages/web-renderer/README.md Install the web renderer package using npm. This is the first step to using it in your web project. ```bash npm install --save @elemaudio/web-renderer ``` -------------------------------- ### Bundle JavaScript for CLI with esbuild Source: https://github.com/elemaudio/elementary/blob/main/cli/README.md Instructions to install npm dependencies and build JavaScript files using esbuild in the examples directory. ```bash cd cli/examples/ npm install npm run build ``` -------------------------------- ### Example: List Available Samples Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Demonstrates how to retrieve and log the list of all file paths currently stored in the virtual file system. ```javascript const files = core.listVirtualFileSystem(); console.log('Available samples:', files); ``` -------------------------------- ### Install @elemaudio/offline-renderer Source: https://github.com/elemaudio/elementary/blob/main/js/packages/offline-renderer/README.md Install the offline renderer package using npm. ```bash npm install --save @elemaudio/offline-renderer ``` -------------------------------- ### Example: Load WAV and Update VFS Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Shows how to load a WAV file using 'wav-decoder', decode it, and add the audio data to the renderer's virtual file system. The updated VFS can then be used in audio graphs. ```javascript // Load WAV file and add to VFS import wavDecoder from 'wav-decoder'; const buffer = fs.readFileSync('sample.wav'); const decoded = await wavDecoder.decode(buffer); // Get first channel (mono) or channels const channels = decoded.channelData; // Add to renderer const result = core.updateVirtualFileSystem({ 'sample.wav': channels[0] }); if (result.success) { // Now can use in graphs await core.render( el.sample({path: 'sample.wav'}, el.constant({value: 1}), el.constant({value: 1})) ); } ``` -------------------------------- ### Initialize OfflineRenderer with Minimal Configuration Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Demonstrates initializing the OfflineRenderer with only the essential `sampleRate` option. This is useful for basic rendering setups. ```javascript import OfflineRenderer from '@elemaudio/offline-renderer'; import { el } from '@elemaudio/core'; const core = new OfflineRenderer(); // Minimal configuration await core.initialize({ sampleRate: 44100 }); ``` -------------------------------- ### Example: Set Playback Time to 10 Seconds Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Sets the engine's current playback time to 10 seconds. ```javascript core.setCurrentTime(10); ``` -------------------------------- ### Initialize for CPU-Constrained Devices Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Configure Elementary Audio for devices with limited CPU resources. This setup balances performance by using a moderate block size and a lower sample rate. ```javascript await core.initialize({ blockSize: 1024, sampleRate: 22050, numOutputChannels: 1 }); ``` -------------------------------- ### Initialize WebRenderer with AudioWorkletNodeOptions Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/types.md Example of initializing the WebRenderer with specific AudioWorkletNode options. This configures the audio processing graph for the web environment. ```javascript const worklet = await core.initialize(ctx, { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [2] }); ``` -------------------------------- ### Run Bundled JavaScript with Elementary CLI Source: https://github.com/elemaudio/elementary/blob/main/cli/README.md Example command to execute a bundled JavaScript file using the elemcli binary. Adjust the path to elemcli based on your build directory structure. ```bash # Your path to the elemcli binary might be different depending on your build # directory structure ./build/cli/Debug/elemcli examples/dist/00_HelloSine.js ``` -------------------------------- ### Example: Prune VFS Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Executes the prune operation on the virtual file system to remove any unreferenced audio samples. ```javascript core.pruneVirtualFileSystem(); ``` -------------------------------- ### Example: Reset Renderer Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Calls the reset function to clear the current state of the audio engine. ```javascript core.reset(); ``` -------------------------------- ### Example: Sweeping Frequency with createRef Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Demonstrates how to use createRef to dynamically sweep a frequency parameter during audio processing. The returned setter function allows updating node properties. ```javascript // Sweeping frequency const [freqNode, setFreq] = core.createRef('const', {value: 200}, []); const sweep = el.mul( el.cycle(freqNode), el.mul(0.3, el.hann(el.phasor(el.constant({value: 1})))) ); await core.render(sweep, sweep); // Update frequency during processing const sampleCount = 44100 * 5; const left = new Float32Array(sampleCount); const right = new Float32Array(sampleCount); // Sweep frequency from 200 to 800 Hz for (let f = 200; f <= 800; f += 20) { setFreq({value: f}); // Process a chunk } core.process([], [left, right]); ``` -------------------------------- ### ElemNode Usage Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/types.md Demonstrates valid ElemNode values, showing how to pass both node representations and numeric literals. ```javascript // Both are valid ElemNode values el.add(el.cycle(440), 0.5); // NodeRepr_t | number el.mul(10, el.phasor(1)); // number | NodeRepr_t ``` -------------------------------- ### Initialize OfflineRenderer with Full Configuration Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Shows how to initialize the OfflineRenderer with all available configuration options, including input/output channels, sample rate, block size, and a virtual file system. This allows for advanced setups with custom audio assets. ```javascript import OfflineRenderer from '@elemaudio/offline-renderer'; import { el } from '@elemaudio/core'; const core = new OfflineRenderer(); // Full configuration await core.initialize({ numInputChannels: 2, numOutputChannels: 2, sampleRate: 48000, blockSize: 256, virtualFileSystem: { 'loop1.wav': loopBuffer, 'loop2.wav': loopBuffer2 } }); ``` -------------------------------- ### Example: Perform Garbage Collection Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Executes the garbage collection process and logs the number of nodes that were removed. ```javascript const pruned = core.gc(); console.log('Removed', pruned.length, 'nodes'); ``` -------------------------------- ### Initialize and Use OfflineRenderer Source: https://github.com/elemaudio/elementary/blob/main/js/packages/offline-renderer/README.md Initialize the OfflineRenderer, set up processing parameters, and render audio data. This example demonstrates creating a silent 10-second audio buffer. ```javascript import { el } from '@elemaudio/core'; import OfflineRenderer from '@elemaudio/offline-renderer'; (async function main() { let core = new OfflineRenderer(); await core.initialize({ numInputChannels: 0, numOutputChannels: 1, sampleRate: 44100, }); // Our sample data for processing: an empty input and a silent 10s of // output data to be written into. let inps = []; let outs = [new Float32Array(44100 * 10)]; // 10 seconds of output data // Render our processing graph core.render(el.cycle(440)); // Pushing samples through the graph. After this call, the buffer in `outs` will // have the desired output data which can then be saved to file if you like. core.process(inps, outs); })(); ``` -------------------------------- ### Initialize for Low-Latency Interactive App Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Configure Elementary Audio for a low-latency interactive application. This setup prioritizes responsiveness with a smaller block size and standard sample rate. ```javascript await core.initialize({ blockSize: 128, sampleRate: 44100, numOutputChannels: 1 }); ``` -------------------------------- ### Example: Set Playback Time to 5000 Milliseconds Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Sets the engine's current playback time to 5000 milliseconds (5 seconds). ```javascript core.setCurrentTimeMs(5000); ``` -------------------------------- ### Initialize for High-Quality Offline Rendering Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Configure Elementary Audio for high-quality offline rendering. This setup uses a larger block size and a higher sample rate to maximize audio fidelity. ```javascript await core.initialize({ blockSize: 2048, sampleRate: 96000, numOutputChannels: 2 }); ``` -------------------------------- ### RenderStats Usage Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/types.md Logs statistics after a render operation, showing the elapsed time and the number of nodes and edges added. ```javascript const stats = await core.render(el.cycle(440), el.cycle(441)); console.log(`Rendered in ${stats.elapsedTimeMs}ms`); console.log(`Added ${stats.nodesAdded} nodes, ${stats.edgesAdded} edges`); ``` -------------------------------- ### time() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Returns elapsed time in seconds since the start of the audio engine. This node provides the current time. ```APIDOC ## time() ### Description Returns elapsed time in seconds since the start of the audio engine. ### Signature ```typescript function time(): NodeRepr_t ``` ### Parameters #### Path Parameters * None #### Query Parameters * None ### Request Example ```javascript // Get elapsed time const elapsed = el.time(); ``` ### Response #### Success Response (200) * **NodeRepr_t** - Time node #### Response Example * None explicitly defined, but returns a NodeRepr_t object. ``` -------------------------------- ### Basic ADSR Envelope Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/envelopes.md Demonstrates creating a basic ADSR envelope with fixed times using el.adsr(). This is useful for standard amplitude shaping. ```javascript import { el } from '@elemaudio/core'; // Basic ADSR with fixed times const envelope = el.adsr( el.constant({value: 0.1}), // 100ms attack el.constant({value: 0.2}), // 200ms decay el.constant({value: 0.6}), // 60% sustain level el.constant({value: 0.5}), // 500ms release el.metro({interval: 500}) // Gate on every 500ms ); // Use to shape a synthesizer voice const voice = el.mul( el.cycle(el.constant({value: 440})), envelope ); ``` -------------------------------- ### Render Audio Graph with Simple Tone Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Renders an audio graph to produce a simple tone. This example demonstrates basic graph rendering using the el.cycle and el.constant functions. ```javascript import { el } from '@elemaudio/core'; // Simple tone await core.render( el.cycle(el.constant({value: 440})), el.cycle(el.constant({value: 441})) ); ``` -------------------------------- ### Process Multichannel Sample Independently Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/multichannel.md Loads a sample and processes each channel individually. This example reduces the volume of the left channel. ```javascript const processed = el.mc.sample( {path: "drums.wav", channels: 2}, el.constant({value: 1}) ).map((ch, i) => { // Reduce volume of left channel return el.mul(ch, i === 0 ? 0.8 : 1.0); }); ``` -------------------------------- ### Render Simple Tones and Effects Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/web-renderer.md Renders audio graphs to the Web Audio API. This example demonstrates rendering simple tones and applying effects like a low-pass filter. ```javascript // Simple tone await core.render( el.cycle(el.constant({value: 440})), el.cycle(el.constant({value: 441})) ); // With effects const filtered = el.lowpass( el.constant({value: 1000}), el.constant({value: 1}), el.cycle(el.constant({value: 440})) ); await core.render(filtered, filtered); ``` -------------------------------- ### Soft Knee Compressor Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/dynamics.md Demonstrates the usage of the skcompress function for various soft-knee compression scenarios, including transparent compression, punchy effects, and sidechain compression. Ensure the '@elemaudio/core' library is imported. ```javascript import { el } from '@elemaudio/core'; // Soft knee compressor const input = el.identity({channel: 0}); const softCompressed = el.skcompress( el.constant({value: 10}), // 10ms attack el.constant({value: 100}), // 100ms release el.constant({value: -20}), // -20dB threshold el.constant({value: 4}), // 4:1 ratio el.constant({value: 6}), // 6dB soft knee input, // Sidechain input // Input to compress ); // Wide soft knee for transparent compression const transparent = el.skcompress( el.constant({value: 50}), el.constant({value: 200}), el.constant({value: -30}), el.constant({value: 2}), el.constant({value: 12}), // Wide 12dB knee input, input ); // Tight soft knee for more noticeable effect const punchy = el.skcompress( el.constant({value: 5}), el.constant({value: 50}), el.constant({value: -15}), el.constant({value: 6}), el.constant({value: 2}), // Narrow 2dB knee input, input ); // Sidechain compression with soft knee const vocal = el.identity({channel: 0}); const sidechain = el.identity({channel: 1}); const reduced = el.skcompress( el.constant({value: 20}), el.constant({value: 150}), el.constant({value: -25}), el.constant({value: 3}), el.constant({value: 8}), sidechain, vocal ); ``` -------------------------------- ### Play Sample with Metro Trigger Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Example of using the sample function to play a WAV file triggered by a metro object. The playback rate is set to a constant value. ```javascript const sample = el.sample( {path: "loop.wav"}, el.metro({interval: 500}), el.constant({value: 1}) ); ``` -------------------------------- ### Bandpass Filter Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/filters.md Apply a bandpass filter to isolate frequencies within a specific range. Configure the center frequency, Q factor, and input signal. ```javascript // Bandpass filter centered at 1000 Hz, Q of 5 const filtered = el.bandpass( el.constant({value: 1000}), el.constant({value: 5}), el.cycle(440) ); ``` -------------------------------- ### Dynamic ADSR Envelope Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/envelopes.md Shows how to create a dynamic ADSR envelope where parameters like attack, decay, sustain, and release times can be controlled programmatically. This allows for flexible envelope shaping. ```javascript const attackTime = el.constant({value: 0.05}); const decayTime = el.constant({value: 0.15}); const sustainLevel = el.constant({value: 0.7}); const releaseTime = el.constant({value: 1.0}); const gate = el.constant({value: 1}); const dynamic = el.adsr( attackTime, decayTime, sustainLevel, releaseTime, gate ); ``` -------------------------------- ### Compressor Implementation Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/dynamics.md This snippet demonstrates how to implement a basic hard knee compressor using the el.compress function. It shows examples for standard compressor behavior, using an external sidechain, gentle compression for level consistency, and aggressive compression for peak limiting. ```typescript function compress( attackMs: ElemNode, releaseMs: ElemNode, threshold: ElemNode, ratio: ElemNode, sidechain: ElemNode, xn: ElemNode, ): NodeRepr_t ``` ```javascript import { el } from '@elemaudio/core'; // Basic compressor on audio input const input = el.identity({channel: 0}); const compressed = el.compress( el.constant({value: 10}), // 10ms attack el.constant({value: 100}), // 100ms release el.constant({value: -20}), // -20dB threshold el.constant({value: 4}), // 4:1 ratio input, // Same signal for sidechain and input input // Signal to compress ); // Compressor with external sidechain const audio = el.identity({channel: 0}); const sidechain = el.identity({channel: 1}); const sideChainCompressed = el.compress( el.constant({value: 5}), el.constant({value: 50}), el.constant({value: -15}), el.constant({value: 2}), sidechain, // Use channel 1 to control compression audio // Compress channel 0 ); // Gentle compression for consistent levels const gentle = el.compress( el.constant({value: 50}), el.constant({value: 200}), el.constant({value: -30}), el.constant({value: 1.5}), input, input ); // Aggressive compression for peak limiting const limiter = el.compress( el.constant({value: 1}), el.constant({value: 50}), el.constant({value: -6}), el.constant({value: 8}), input, input ); ``` -------------------------------- ### Handling WebRenderer Events Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/web-renderer.md Listen for various events emitted by the WebRenderer engine to react to its state changes and data reports. This example demonstrates handling 'load', 'meter', 'snapshot', and 'error' events. ```javascript const core = new WebRenderer(); core.on('load', () => { console.log('Engine ready'); }); core.on('meter', (data) => { console.log('Levels - min:', data.min, 'max:', data.max); }); core.on('snapshot', (data) => { console.log('Snapshot value:', data.data); }); core.on('error', (err) => { console.error('Engine error:', err); }); ``` -------------------------------- ### Initialize and Render Audio with @elemaudio/core Source: https://github.com/elemaudio/elementary/blob/main/js/packages/core/README.md Demonstrates how to import and initialize a Renderer instance from @elemaudio/core, and then render audio using el.cycle to create binaural beating with detuned sine tones. ```javascript import { el, Renderer } from '@elemaudio/core'; // Here we're using a default Renderer instance, so it's our responsibility to // send the instruction batches to the underlying engine let core = new Renderer((batch) => { // Send the instruction batch somewhere: you can set up whatever message // passing channel you want! console.log(batch); }); // Now we can write and render audio. How about some binaural beating // with two detuned sine tones in the left and right channel: core.render(el.cycle(440), el.cycle(441)); ``` -------------------------------- ### Get Elapsed Time Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Retrieves the elapsed time in seconds since the audio engine started. This is a direct call to the 'time()' function. ```javascript // Get elapsed time const elapsed = el.time(); ``` -------------------------------- ### Get Time Node Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Returns the elapsed time in seconds since the start of the audio engine as a node. This is useful for time-based audio effects. ```typescript function time(): NodeRepr_t ``` -------------------------------- ### Build Elementary CLI with CMake Source: https://github.com/elemaudio/elementary/blob/main/cli/README.md Steps to clone the Elementary repository, initialize a build directory, configure with CMake, and build the binaries. ```bash # Get Elementary git clone https://github.com/elemaudio/elementary.git --recurse-submodules cd elementary # Initialize the CMake directory mkdir build/ cd build/ # Choose your favorite CMake generator here cmake -G Xcode -DCMAKE_OSX_DEPLOYMENT_TARGET=10.15 ../ # Build the binaries cmake --build . ``` -------------------------------- ### Initialize and Render with Web Renderer Source: https://github.com/elemaudio/elementary/blob/main/js/packages/web-renderer/README.md Demonstrates how to initialize the WebRenderer with an AudioContext and render audio signals. Ensure user gestures initiate the AudioContext in production environments. ```javascript import { el } from '@elemaudio/core'; import WebRenderer from '@elemaudio/web-renderer'; // Note that many browsers won't let you start an AudioContext before // some corresponding user gesture. We're ignoring that in this example for brevity, // but typically you would add an event callback to make or resume your // AudioContext instance in order to start making noise. const ctx = new AudioContext(); const core = new WebRenderer(); (async function main() { // Here we initialize our WebRenderer instance, returning a promise which resolves // to the WebAudio node containing the runtime let node = await core.initialize(ctx, { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2], }); // And connect the resolved node to the AudioContext destination node.connect(ctx.destination); // Then finally we can render core.render(el.cycle(440), el.cycle(441)); })(); ``` -------------------------------- ### sample() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Plays back a sample from the virtual file system with configurable playback options. ```APIDOC ## sample() ### Description Plays back a sample from the virtual file system. ### Parameters #### Path Parameters - **props** (object) - Required - Configuration object - **path** (string) - Required - Path to sample in virtual file system - **mode** (string) - Optional - Playback mode - **startOffset** (number) - Optional - Start offset in samples - **stopOffset** (number) - Optional - Stop offset in samples - **trigger** (ElemNode) - Required - Trigger to start playback - **rate** (ElemNode) - Required - Playback rate multiplier ### Returns `NodeRepr_t` — Sample playback node ### Request Example ```javascript const sample = el.sample( {path: "loop.wav"}, el.metro({interval: 500}), el.constant({value: 1}) ); ``` ``` -------------------------------- ### Basic WebRenderer Initialization Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Initializes the WebRenderer with default settings and connects it to the audio destination. ```javascript import WebRenderer from '@elemaudio/web-renderer'; import { el } from '@elemaudio/core'; const ctx = new AudioContext(); const core = new WebRenderer(); // Basic initialization const node = await core.initialize(ctx); node.connect(ctx.destination); ``` -------------------------------- ### initialize Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/web-renderer.md Initializes the WebRenderer with a Web Audio context. This method sets up the audio worklet and prepares the renderer for audio processing. ```APIDOC ## initialize() ### Description Initializes the WebRenderer with a Web Audio context. ### Method `async initialize(audioContext: AudioContext, workletOptions?: AudioWorkletNodeOptions, eventInterval?: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **audioContext** (AudioContext) - Required - Web Audio API AudioContext instance - **workletOptions** (AudioWorkletNodeOptions) - Optional - Options for the audio worklet node - **eventInterval** (number) - Optional - Event polling interval in milliseconds (Default: 16) ### Request Example ```javascript import { el } from '@elemaudio/core'; import WebRenderer from '@elemaudio/web-renderer'; const ctx = new AudioContext(); const core = new WebRenderer(); // Initialize and connect to audio output const workletNode = await core.initialize(ctx, { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] }); workletNode.connect(ctx.destination); // Now ready to render await core.render(el.cycle(440), el.cycle(441)); ``` ### Response #### Success Response (200) - **AudioWorkletNode** - The audio worklet node containing the renderer #### Response Example (No specific example provided for the return value structure, but it's an AudioWorkletNode) ### Notes: - The browser must be in a secure context (HTTPS) for audio worklet access - User gesture may be required to resume AudioContext - The returned worklet node should be connected to destination or other nodes ``` -------------------------------- ### reset() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Resets the engine state, clearing all created nodes and graphs. This effectively starts the renderer from a clean slate. ```APIDOC ## reset() ### Description Resets the engine state, clearing all created nodes and graphs. This effectively starts the renderer from a clean slate. ### Signature ```typescript reset(): void ``` ### Request Example ```javascript core.reset(); ``` ``` -------------------------------- ### Import Elementary Core Modules Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Imports the main entry point for Elementary Audio, including the core renderer and utility classes. ```javascript import { el, Renderer } from '@elemaudio/core'; import WebRenderer from '@elemaudio/web-renderer'; import OfflineRenderer from '@elemaudio/offline-renderer'; ``` -------------------------------- ### Get Current Sample Rate Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Retrieves the current sample rate of the audio engine. This is a simple call to the 'sr()' function. ```javascript // Get current sample rate const sampleRate = el.sr(); ``` -------------------------------- ### Initialize for Real-time Monitoring with Low Event Latency Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Initialize Elementary Audio for real-time monitoring, prioritizing low event latency. The 'ctx' parameter and the number of output channels are specified. ```javascript const node = await core.initialize(ctx, {}, 8); // 8ms event polling ``` -------------------------------- ### Highpass Filter Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/filters.md Use the highpass function to filter out low frequencies. Specify the cutoff frequency, Q factor, and the input signal. ```javascript // Highpass filter at 200 Hz const filtered = el.highpass( el.constant({value: 200}), el.constant({value: 1}), el.cycle(440) ); ``` -------------------------------- ### Import All Core Functions Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/node-utilities.md Import all core functions under a namespace for convenient access. Demonstrates usage of createNode, resolve, isNode, and unpack. ```javascript import * as core from '@elemaudio/core'; core.createNode('const', {value: 440}, []); core.resolve(440); core.isNode(node); core.unpack(stereoNode, 2); ``` -------------------------------- ### Initialize WebRenderer with AudioContext Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/web-renderer.md Initializes the WebRenderer with a Web Audio context and connects it to the browser's audio output. Ensure the browser is in a secure context (HTTPS) and be prepared to handle user gestures for AudioContext resumption. ```javascript import { el } from '@elemaudio/core'; import WebRenderer from '@elemaudio/web-renderer'; const ctx = new AudioContext(); const core = new WebRenderer(); // Initialize and connect to audio output const workletNode = await core.initialize(ctx, { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] }); workletNode.connect(ctx.destination); // Now ready to render await core.render(el.cycle(440), el.cycle(441)); ``` -------------------------------- ### Notch Filter Example Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/filters.md Use the notch function to remove a specific frequency, such as hum. Set the notch frequency, Q factor, and the input signal. ```javascript // Notch out 50 Hz hum const denoised = el.notch( el.constant({value: 50}), el.constant({value: 10}), el.identity({channel: 0}) ); ``` -------------------------------- ### WebRenderer Initialization with Audio Input/Output Configuration Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Initializes the WebRenderer specifying the number of audio inputs, outputs, and their channel counts. ```javascript const node2 = await core.initialize(ctx, { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [2] }); ``` -------------------------------- ### Use Counter Node Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Creates a counter node that increments when the gate signal is high. This example uses a constant value of 1 as the gate signal. ```javascript const count = el.counter(el.constant({value: 1})); ``` -------------------------------- ### Web Audio Rendering with Browser Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Initialize the WebRenderer, connect it to the AudioContext, and render stereo sine waves. Use createRef to manage and update audio parameters like frequency. ```javascript import { el } from '@elemaudio/core'; import WebRenderer from '@elemaudio/web-renderer'; const ctx = new AudioContext(); const core = new WebRenderer(); // Initialize and connect const node = await core.initialize(ctx); node.connect(ctx.destination); // Render stereo sine waves await core.render( el.cycle(el.constant({value: 440})), el.cycle(el.constant({value: 441})) ); // Update frequency const [freqNode, setFreq] = core.createRef('const', {value: 440}, []); await core.render(el.cycle(freqNode), el.cycle(freqNode)); await setFreq({value: 550}); ``` -------------------------------- ### Get Sample Rate Node Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Returns the sample rate of the audio engine as a node. This can be used to access the current sample rate within the audio graph. ```typescript function sr(): NodeRepr_t ``` -------------------------------- ### Import Main Exports Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/node-utilities.md Import the main exports including 'el', 'Renderer', and utility functions from @elemaudio/core. ```javascript import { el, Renderer, createNode, resolve, isNode, unpack } from '@elemaudio/core'; ``` -------------------------------- ### Capture Snapshot Values Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Listen for 'snapshot' events to get specific data points captured by analysis nodes. The event data contains the captured value directly. ```javascript core.on('snapshot', (data) => { console.log('Value:', data.data); }); ``` -------------------------------- ### listVirtualFileSystem() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Lists all files currently present in the virtual file system. This can be useful for debugging or understanding what audio assets are available. ```APIDOC ## listVirtualFileSystem() ### Description Lists all files currently present in the virtual file system. This can be useful for debugging or understanding what audio assets are available. ### Signature ```typescript listVirtualFileSystem(): string[] ``` ### Returns - **string[]** — Array of file paths ### Request Example ```javascript const files = core.listVirtualFileSystem(); console.log('Available samples:', files); ``` ``` -------------------------------- ### process() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Processes audio blocks using provided input buffers and fills the output buffers. Input and output arrays must match the configured channel counts. ```APIDOC ## process() ### Description Processes audio blocks. ### Method `process(inputs: Array, outputs: Array): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **inputs** (Float32Array[]) - Required - Input buffers (one per input channel) - **outputs** (Float32Array[]) - Required - Output buffers to fill (one per output channel) ### Request Example ```javascript import OfflineRenderer from '@elemaudio/offline-renderer'; import { el } from '@elemaudio/core'; import * as fs from 'fs'; const core = new OfflineRenderer(); await core.initialize({ numInputChannels: 0, numOutputChannels: 2, sampleRate: 44100, blockSize: 512 }); // Render a 3-second tone await core.render( el.cycle(el.constant({value: 440})), el.cycle(el.constant({value: 441})) ); // Create output buffers for 3 seconds at 44100Hz const sampleCount = 44100 * 3; const left = new Float32Array(sampleCount); const right = new Float32Array(sampleCount); // Process the full duration core.process([], [left, right]); // Now left and right contain the rendered audio console.log('Generated', sampleCount, 'samples'); // Could write to file or use with audio libraries ``` ### Response #### Success Response (200) `void` - Processing is synchronous and modifies output buffers in place. #### Response Example None explicitly provided, output buffers are modified directly. ``` -------------------------------- ### Initialize Renderer Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/renderer.md Instantiate the Renderer with a callback function to send instruction batches to the audio engine. This callback is essential for the engine to receive and process audio graph commands. ```typescript class Renderer { constructor(sendMessage: Function) render(...args: NodeRepr_t[]): Promise renderWithOptions(options: RenderOptions, ...args: NodeRepr_t[]): Promise createRef(kind: string, props: object, children: NodeRepr_t[]): [NodeRepr_t, Function] prune(nodeIds: number[]): void } ``` ```typescript constructor(sendMessage: (batch: Array) => Promise) ``` ```javascript import { Renderer } from '@elemaudio/core'; const core = new Renderer((batch) => { // Send instructions to your audio engine console.log(batch); return Promise.resolve(); }); ``` -------------------------------- ### initialize() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Initializes the offline renderer with specified configuration options such as channel counts, sample rate, block size, and an initial virtual file system. ```APIDOC ## initialize() ### Description Initializes the offline renderer with specified configuration. ### Method `initialize(options: OfflineRendererOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - Configuration object - **numInputChannels** (number) - Optional - Number of input channels (Default: 0) - **numOutputChannels** (number) - Optional - Number of output channels (Default: 2) - **sampleRate** (number) - Optional - Sample rate in Hz (Default: 44100) - **blockSize** (number) - Optional - Processing block size (Default: 512) - **virtualFileSystem** (object) - Optional - Initial VFS samples (Default: {}) ### Request Example ```javascript import OfflineRenderer from '@elemaudio/offline-renderer'; import { el } from '@elemaudio/core'; const core = new OfflineRenderer(); // Initialize with custom settings await core.initialize({ numInputChannels: 0, numOutputChannels: 2, sampleRate: 48000, blockSize: 256 }); // Initialize with samples await core.initialize({ sampleRate: 44100, numOutputChannels: 2, virtualFileSystem: { 'loop.wav': loopBuffer, 'drums.wav': drumsBuffer } }); ``` ### Response #### Success Response (200) `Promise` — Resolves when initialization is complete #### Response Example None explicitly provided, resolves on success. ``` -------------------------------- ### Renderer Constructor Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/renderer.md Creates a new Renderer instance. It requires a callback function to send instruction batches to the audio engine. ```APIDOC ## Renderer Constructor ### Description Creates a new Renderer instance. It requires a callback function to send instruction batches to the audio engine. ### Method ```typescript constructor(sendMessage: Function) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Constructor Parameters - **sendMessage** (Function) - Required - Callback to send instruction batches to the engine ### Request Example ```javascript import { Renderer } from '@elemaudio/core'; const core = new Renderer((batch) => { // Send instructions to your audio engine console.log(batch); return Promise.resolve(); }); ``` ``` -------------------------------- ### Generic Renderer with Custom Engine Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Integrate Elementary with a custom audio engine by providing a callback function to the Renderer constructor. This callback receives batches of instructions to be processed by the custom engine. ```javascript import { el, Renderer } from '@elemaudio/core'; const core = new Renderer((batch) => { // Send instructions to your custom audio engine console.log(batch); return Promise.resolve(); }); await core.render( el.cycle(440), el.cycle(441) ); ``` -------------------------------- ### Configuration Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Options for configuring renderers and nodes. ```APIDOC ## Configuration ### Description Covers configuration options for renderers and nodes. ### Options - `OfflineRenderer` initialization options. - `WebRenderer` worklet options. - Render transition options. - Virtual file system management. - Performance tuning. ``` -------------------------------- ### Get Maximum of Multiple Values Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/math.md Use `el.max()` to find the largest value among several inputs. This function takes an array of `ElemNode` values and returns a `NodeRepr_t` representing the maximum. ```typescript function max(...args: Array): NodeRepr_t ``` ```javascript const threshold = el.max(el.cycle(440), 0.1); ``` -------------------------------- ### Initialize OfflineRenderer with Virtual File System Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Initializes the offline renderer and populates the virtual file system with audio samples. All VFS data must be provided as Float32Array. ```javascript import OfflineRenderer from '@elemaudio/offline-renderer'; import { el } from '@elemaudio/core'; const core = new OfflineRenderer(); // Initialize with samples await core.initialize({ sampleRate: 44100, numOutputChannels: 2, virtualFileSystem: { 'loop.wav': loopBuffer, 'drums.wav': drumsBuffer } }); ``` -------------------------------- ### listVirtualFileSystem() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/web-renderer.md Lists all loaded files currently present in the virtual file system. ```APIDOC ## listVirtualFileSystem() ### Description Lists all loaded files in the virtual file system. ### Method `async` ### Parameters None ### Request Example ```javascript const files = await core.listVirtualFileSystem(); console.log('Loaded samples:', files); ``` ### Response #### Success Response - **File Paths** (string[]) - Array of file paths ``` -------------------------------- ### Play Audio Sample from VFS Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Use the el.sample node to play back an audio file stored in the virtual file system. Ensure the path matches the VFS entry exactly. Supports basic playback triggered by a metronome. ```javascript // Sample playback node const sample = el.sample( {path: 'loop.wav'}, el.metro({interval: 500}), el.constant({value: 1}) ); ``` -------------------------------- ### Create and Modulate Sine Wave Oscillator Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/oscillators.md Use el.cycle to create a sine wave oscillator at a specified frequency. This example also shows how to modulate the frequency of the sine wave using another oscillator. ```javascript import { el } from '@elemaudio/core'; // Create a 440 Hz sine wave const sine = el.cycle(el.constant({value: 440})); // Modulate the frequency const lfo = el.cycle(el.constant({value: 5})); const modulated = el.cycle(el.add(440, el.mul(lfo, 10))); ``` -------------------------------- ### Node Utilities Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/SUMMARY.txt Documentation for low-level node creation utilities such as createNode, resolve, isNode, and unpack. ```APIDOC ## Node Utilities ### Description Provides low-level utility functions for creating and manipulating audio nodes. ### Functions - `createNode`: Creates a new audio node. - `resolve`: Resolves a node or its properties. - `isNode`: Checks if a value is a valid node. - `unpack`: Unpacks node data. ``` -------------------------------- ### Play Multichannel Audio Sample from VFS Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Use el.mc.sample for multichannel audio files, specifying the number of channels. The path must match the VFS entry. ```javascript // Multichannel sample const [l, r] = el.mc.sample( {path: 'stereo.wav', channels: 2}, el.constant({value: 1}) ); ``` -------------------------------- ### WebRenderer Initialization Signature Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Shows the signature for initializing the WebRenderer, including optional parameters. ```typescript initialize( audioContext: AudioContext, workletOptions?: AudioWorkletNodeOptions, eventInterval?: number ): Promise ``` -------------------------------- ### Import Individual Functions Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/node-utilities.md Import specific functions like createNode, resolve, isNode, and unpack from the @elemaudio/core package. ```javascript import { createNode, resolve, isNode, unpack } from '@elemaudio/core'; ``` -------------------------------- ### Multichannel Utilities Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/SUMMARY.txt Documentation for 5 multichannel utilities within the 'mc' namespace, such as mc.sample, mc.table, and mc.capture. ```APIDOC ## Multichannel Utilities ### Description Provides 5 utility functions for handling multichannel audio signals under the `mc` namespace. ### Utilities (mc namespace) - `mc.sample`: Multichannel sample playback. - `mc.table`: Multichannel table lookup. - `mc.capture`: Multichannel audio capture. ``` -------------------------------- ### updateVirtualFileSystem() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Adds or updates audio samples in the virtual file system. This allows you to load custom audio files and use them within your audio graphs. ```APIDOC ## updateVirtualFileSystem() ### Description Adds or updates audio samples in the virtual file system. This allows you to load custom audio files and use them within your audio graphs. ### Signature ```typescript updateVirtualFileSystem(vfs: {[key: string]: Float32Array | Array}): {success: boolean, message: string} ``` ### Parameters #### Path Parameters - **vfs** (object) - Required - Map of file paths to audio buffers ### Returns - **{success: boolean, message: string}** — Operation result ### Request Example ```javascript // Load WAV file and add to VFS import wavDecoder from 'wav-decoder'; const buffer = fs.readFileSync('sample.wav'); const decoded = await wavDecoder.decode(buffer); // Get first channel (mono) or channels const channels = decoded.channelData; // Add to renderer const result = core.updateVirtualFileSystem({ 'sample.wav': channels[0] }); if (result.success) { // Now can use in graphs await core.render( el.sample({path: 'sample.wav'}, el.constant({value: 1}), el.constant({value: 1})) ); } ``` ``` -------------------------------- ### render() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/renderer.md Renders one or more nodes as the audio graph outputs. Default fade times are 20ms in and 20ms out. ```APIDOC ## render() ### Description Renders one or more nodes as the audio graph outputs. Default fade times are 20ms in and 20ms out. ### Method ```typescript render(...args: NodeRepr_t[]): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Render Parameters - **...args** (NodeRepr_t[]) - Required - Root nodes to render as outputs ### Returns `Promise` — Statistics about the render pass **RenderStats Object:** - **nodesAdded** (number) - Count of nodes added in this render - **edgesAdded** (number) - Count of edges/connections added - **propsWritten** (number) - Count of properties updated - **elapsedTimeMs** (number) - Time taken for render pass in milliseconds - **result** (any) - Result from sendMessage callback ### Request Example ```javascript import { el, Renderer } from '@elemaudio/core'; const core = new Renderer((batch) => { // Process instructions return Promise.resolve(); }); // Render stereo output await core.render( el.cycle(440), // Left channel el.cycle(441) // Right channel ); // Single mono output await core.render(el.cycle(440)); // Complex graph await core.render( el.lowpass( el.constant({value: 1000}), el.constant({value: 1}), el.cycle(440) ), el.cycle(441) ); ``` ``` -------------------------------- ### tapIn() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Creates a feedback path input point. This function is used to define where a feedback signal will enter the audio graph. ```APIDOC ## tapIn() ### Description Creates a feedback path input point. ### Signature ```typescript function tapIn(props: { key?: string; name: string }): NodeRepr_t ``` ### Parameters #### Props - **name** (string) - Required - Unique name for the feedback tap. - **key** (string) - Optional - Optional unique identifier. ### Returns `NodeRepr_t` — Tap input node ### Example ```javascript const feedback = el.tapIn({name: "delayFeedback"}); ``` ``` -------------------------------- ### Delegate Class Methods Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/renderer.md Provides methods to manage and commit rendering instructions for the renderer. ```APIDOC ## Delegate Class ### Description Internal delegate that accumulates rendering instructions. ### Methods - `clear()` — Reset instruction batch and counters - `getNodeMap()` — Retrieve the internal node mapping - `createNode(hash, type)` — Record node creation instruction - `appendChild(parentHash, childHash, childOutputChannel)` — Record edge creation - `setProperty(hash, key, value)` — Record property update - `activateRoots(roots)` — Record root activation - `commitUpdates()` — Record commit instruction - `getPackedInstructions()` — Get all accumulated instructions ``` -------------------------------- ### Play Sample on Trigger Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/README.md Loads a WAV sample into the virtual file system and plays it back when triggered by a metronome. Playback rate can be controlled. ```javascript // Add sample to VFS await core.updateVirtualFileSystem({ 'loop.wav': loopBuffer }); // Play on metro trigger const sample = el.sample( {path: 'loop.wav'}, el.metro({interval: 2000}), el.constant({value: 1}) // Playback rate ); await core.render(sample, sample); ``` -------------------------------- ### Create Feedback Input Point with tapIn() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/core.md Use tapIn to create an input point for a feedback path. It requires a unique name for the feedback tap. ```typescript function tapIn(props: { key?: string; name: string }): NodeRepr_t ``` ```javascript const feedback = el.tapIn({name: "delayFeedback"}); ``` -------------------------------- ### Basic Multichannel Sample Sequencer Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/multichannel.md Use `mc.sampleseq()` to play multiple samples based on a time-based sequence. Specify the sample path, number of channels, the sequence of values and times, and the total duration. ```javascript const [l, r] = el.mc.sampleseq( { path: "loop.wav", channels: 2, seq: [ {value: 0, time: 0}, {value: 1, time: 0.5} ], duration: 1.0 }, el.time() ); ``` -------------------------------- ### render() Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/api-reference/offline-renderer.md Renders the audio graph by processing the root nodes provided as arguments and returns render statistics. ```APIDOC ## render() ### Description Renders the audio graph. ### Method `render(...args: NodeRepr_t[]): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **...args** (NodeRepr_t[]) - Required - Root nodes to render as outputs ### Request Example ```javascript import { el } from '@elemaudio/core'; // Simple tone await core.render( el.cycle(el.constant({value: 440})), el.cycle(el.constant({value: 441})) ); ``` ### Response #### Success Response (200) `Promise` — Render statistics #### Response Example None explicitly provided, returns render statistics upon completion. ``` -------------------------------- ### Signal Utilities Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/SUMMARY.txt Documentation for 6 signal utility functions for time/amplitude conversion, selection, and windowing. ```APIDOC ## Signal Utilities ### Description Provides 6 utility functions for manipulating audio signals. ### Utilities - Time/amplitude conversion functions. - Signal selection functions. - Windowing functions. ``` -------------------------------- ### WebRenderer Options Interface Source: https://github.com/elemaudio/elementary/blob/main/_autodocs/configuration.md Defines the structure for configuration options passed to WebRenderer.initialize(). ```typescript interface WebRendererOptions { numberOfInputs?: number numberOfOutputs?: number outputChannelCount?: number[] eventInterval?: number } ```