All articles

Procedural audio: PCM samples, WAV files and Godot audio buses

Sample rate and PCM, phase-accumulating oscillators and envelopes, seeded noise and one-pole filters, click-free loops, the RIFF/WAV header, decibels and AudioServer buses.

t.Turgay
Procedural audio: PCM samples, WAV files and Godot audio buses

Short game effects can be generated from code instead of recorded. Sound then becomes an array of numbers sampled at equal intervals; oscillators, noise, filters and envelopes shape that array. Regenerating the same file from the same seed keeps the asset pipeline auditable. The examples below are independent fragments: synthesis and WAV writing in Node.js, and audio buses in Godot C#.

Sample rate, PCM and headroom

At 48 kHz, one second of mono audio is 48,000 numbers. The highest representable frequency is half the sample rate; components above it fold back to lower frequencies and produce audible distortion. During synthesis, values stay in floating point and the range from -1 to 1 is treated as full scale.

Before writing a file, measure the peak and scale the signal to a target peak level; -1 dBFS, for example, leaves a little headroom. Then convert the values to 16-bit signed integers. Clipping before scaling flattens the tops of the waveform and creates harsh distortion.

Phase accumulation and envelopes

At a constant frequency, sin(2πft) is enough. If the frequency changes over time, the phase must advance by the current frequency at every sample; otherwise sudden phase jumps are heard as clicks. An envelope shapes loudness over time: a short attack prevents an onset click and an exponential decay gives a natural tail.

The function below produces a falling frequency sweep. Attack and decay constants are expressed in seconds, so the sound keeps its duration if the sample rate changes.

// Independent example: a falling sweep with an attack/decay envelope.
const SR = 48000;

function sweep(seconds, startHz, endHz) {
  const n = Math.round(SR * seconds);
  const out = new Float64Array(n);
  let phase = 0;
  for (let i = 0; i < n; i++) {
    const t = i / SR;
    const hz = endHz + (startHz - endHz) * Math.exp(-t * 12); // glide toward endHz
    phase += (2 * Math.PI * hz) / SR;                          // accumulate phase
    const envelope = (1 - Math.exp(-t * 900)) * Math.exp(-t * 6);
    out[i] = Math.sin(phase) * envelope;
  }
  return out;
}

Seeded noise and one-pole filters

Effects such as explosions, wind or shields use raw white noise after filtering. Choosing a small seeded generator instead of Math.random makes the same asset identifier produce the same bytes on every build. The file's SHA-256 hash can be stored in a manifest and compared with the next build.

A one-pole low-pass filter has the form y += a·(x − y), where a = 1 − e^(−2πf/sample rate) ties it to the cutoff frequency. The difference between two low-pass filters with different cutoffs gives a band-passed noise bed. These filters are cheap and need only a few operations per sample.

Click-free loops

In looping sounds such as an engine hum, the last sample must flow into the first one. With a steady tone, round the frequency so that a whole number of periods fits in the loop length. Modulations written with angles divided by the loop length, as 2π·i/n, also return to the same value at the wrap point.

Filtered noise can still end at a different value from where it starts. Spreading the remaining difference linearly over the last few hundred samples closes the seam. A validation step can then measure the gap between the first and last samples and expect zero for loop files.

Writing the RIFF/WAV header

A PCM WAV file is a 44-byte header followed by samples. The RIFF chunk carries the total size; the fmt chunk carries the format code (1 for PCM), channel count, sample rate, bytes per second, block alignment and bits per sample. The data chunk holds the raw samples. All multi-byte fields are little-endian.

With more than one channel, samples are interleaved in channel order. Byte rate and block align are derived from the channel count and bytes per sample. If they are wrong, some players still open the file but report the wrong duration.

const fs = require('node:fs');

// samples: Float64Array in -1..1, interleaved when channels > 1
function writeWav16(file, samples, sampleRate, channels = 1) {
  const peak = samples.reduce((m, v) => Math.max(m, Math.abs(v)), 0) || 1;
  const gain = Math.pow(10, -1 / 20) / peak;                 // normalize to -1 dBFS
  const pcm = Buffer.alloc(samples.length * 2);
  samples.forEach((v, i) => pcm.writeInt16LE(Math.round(v * gain * 32767), i * 2));

  const h = Buffer.alloc(44);
  h.write('RIFF', 0); h.writeUInt32LE(36 + pcm.length, 4); h.write('WAVE', 8);
  h.write('fmt ', 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20);
  h.writeUInt16LE(channels, 22); h.writeUInt32LE(sampleRate, 24);
  h.writeUInt32LE(sampleRate * channels * 2, 28);              // byte rate
  h.writeUInt16LE(channels * 2, 32); h.writeUInt16LE(16, 34);  // block align, bits
  h.write('data', 36); h.writeUInt32LE(pcm.length, 40);
  fs.writeFileSync(file, Buffer.concat([h, pcm]));
}

writeWav16('sweep.wav', sweep(0.6, 900, 140), 48000);

Microsoft Learn — WAVEFORMATEX

Decibels and Godot audio buses

A decibel value is 20·log10 of an amplitude ratio: -6 dB is roughly half amplitude and -18 dB roughly one eighth. Settings sliders usually produce a linear value between 0 and 1; Mathf.LinearToDb converts it to a bus level. Because a linear zero maps to minus infinity decibels, muting the bus is a clearer way to express silence.

In Godot, each player sends to a bus and buses flow into Master. Keeping music, effects and UI sounds on separate buses lets players adjust them independently and lets effects and compressors work per bus. A per-event cooldown and a maximum voice count also keep the same effect from stacking up.

using Godot;

public static class AudioBuses
{
    public static void Ensure(params string[] names)
    {
        foreach (var name in names)
        {
            if (AudioServer.GetBusIndex(name) >= 0) continue;
            AudioServer.AddBus();
            int index = AudioServer.BusCount - 1;
            AudioServer.SetBusName(index, name);
            AudioServer.SetBusSend(index, "Master");
        }
    }

    public static void SetVolume(string name, float linear)
    {
        int index = AudioServer.GetBusIndex(name);
        AudioServer.SetBusMute(index, linear <= 0f);
        if (linear > 0f) AudioServer.SetBusVolumeDb(index, Mathf.LinearToDb(linear));
    }
}

// AudioBuses.Ensure("Music", "SFX", "UI");  then: player.Bus = "SFX";

Godot — Audio buses

Related technical articles

You have reached the end of this orbit.
Explore more articles
turgay.A little code, a few pixels, a lot of curiosity.© 2026 · Made on Earth