Noise Module — Cached Noise Source

Provides white noise using a per-sample-rate cached buffer. The buffer is created once per AudioContext.sampleRate and reused, avoiding the overhead of generating random samples on every trigger.

Files

static/js/synth/modules/noise.js

Exports

Export Signature Purpose
build (ctx, params) Returns empty node set (no persistent nodes needed)
createNoiseSource (ctx) Returns a BufferSource with the cached noise buffer (NOT started or connected)
trigger (nodes, ctx, params, time, key) Creates a noise source with envelope, returns { source, gain, output }

Caching

function getNoiseBuf(ctx) {
  if (!_noiseBufs[ctx.sampleRate]) {
    var len = Math.ceil(ctx.sampleRate * 2);
    var buf = ctx.createBuffer(1, len, ctx.sampleRate);
    var d = buf.getChannelData(0);
    for (var i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
    _noiseBufs[ctx.sampleRate] = buf;
  }
  return _noiseBufs[ctx.sampleRate];
}

A 2-second buffer is generated once per sample rate and stored in a module-level cache (_noiseBufs). The same buffer is shared across all triggers.

createNoiseSource

Used by trigger() functions in kick, snare, hihat, and BIA Clone engines. Returns a BufferSource (not looped) that the caller configures (gain envelope, filters, connections) and starts.

trigger

For engines that use the standard noise pattern (mix + decay envelope):

var n = noiseMod.trigger(null, ctx, params, time, key);
if (n) n.output.connect(nextNode);

Uses the key parameter to look up params[key] (mix) and params[key.replace('Mix', 'Decay')] (decay).

Integration

Engines import * as noiseMod from '../modules/noise.js' and call noiseMod.createNoiseSource(ctx) or noiseMod.trigger(...).