Skip to content
1        10        20        30        40        50        60        70        80        90        1001let ctx = null;2let noise = null;3let bus = null;4let verb = null;5let echo = null;6let lastGroan = 0;7let alarmT = 40;8let volume = 0.7;910const rand = (a, b) => a + Math.random() * (b - a);1112// Master volume, 0 to 1. Takes effect right away and again when audio starts.13export function setVolume(v) {14  volume = v * 0.7;15  if (bus) bus.gain.value = volume;16}1718export function initAudio() {19  if (ctx) {20    if (ctx.state === 'suspended') ctx.resume();21    return;22  }23  const AC = window.AudioContext || window.webkitAudioContext;24  if (!AC) return;25  ctx = new AC();2627  // Long white-noise buffer. Each burst reads it from a random spot (see burst),28  // so no two shots or impacts share the same noise.29  const len = Math.floor(ctx.sampleRate * 2);30  noise = ctx.createBuffer(1, len, ctx.sampleRate);31  const data = noise.getChannelData(0);32  for (let i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;3334  // Shared output: everything goes through a light compressor so loud shots35  // don't clip when a dozen zombies groan at once.36  const comp = ctx.createDynamicsCompressor();37  comp.threshold.value = -12;38  comp.ratio.value = 3;39  comp.connect(ctx.destination);40  bus = ctx.createGain();41  bus.gain.value = volume;42  bus.connect(comp);4344  // Room-style reverb. Shots and impacts send a share of their signal into it,45  // so each gunshot rolls off across the streets instead of stopping dead.46  verb = ctx.createConvolver();47  verb.buffer = impulse(2.8, 3);48  const wet = ctx.createGain();49  wet.gain.value = 0.6;50  verb.connect(wet).connect(comp);5152  // Shared echo for distant sounds. Repeats fade out and get duller each time,53  // like sound bouncing off buildings a long way off.54  echo = ctx.createDelay(1);55  echo.delayTime.value = 0.27;56  const feedback = ctx.createGain();57  feedback.gain.value = 0.4;58  const echoTone = ctx.createBiquadFilter();59  echoTone.type = 'lowpass';60  echoTone.frequency.value = 1800;61  const echoOut = ctx.createGain();62  echoOut.gain.value = 0.5;63  echo.connect(echoTone);64  echoTone.connect(feedback).connect(echo);65  echoTone.connect(echoOut).connect(verb);66  echoOut.connect(bus);6768  startWind();69}7071function impulse(seconds, decay) {72  const len = Math.floor(ctx.sampleRate * seconds);73  const buf = ctx.createBuffer(2, len, ctx.sampleRate);74  for (let c = 0; c < 2; c++) {75    const d = buf.getChannelData(c);76    for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, decay);77  }78  return buf;79}8081function burst({ freq, dur, gain, type = 'lowpass', q = 1, delay = 0, wet = 0.25 }) {82  if (!ctx) return;83  const start = ctx.currentTime + delay;84  const src = ctx.createBufferSource();85  src.buffer = noise;86  // Random start point and a little pitch wobble, so repeated sounds differ.87  src.playbackRate.value = rand(0.92, 1.08);88  const filter = ctx.createBiquadFilter();89  filter.type = type;90  filter.frequency.value = freq;91  filter.Q.value = q;92  const g = ctx.createGain();93  g.gain.setValueAtTime(gain, start);94  g.gain.exponentialRampToValueAtTime(0.0001, start + dur);95  src.connect(filter).connect(g).connect(bus);96  if (wet > 0) {97    const send = ctx.createGain();98    send.gain.value = wet;99    g.connect(send).connect(verb);100  }101  src.start(start, rand(0, noise.duration - 1));102  src.stop(start + dur + 0.05);103}104105function sweep({ type = 'sine', f0, f1, dur, gain, delay = 0, wet = 0.2 }) {106  if (!ctx) return;107  const start = ctx.currentTime + delay;108  const osc = ctx.createOscillator();109  osc.type = type;110  osc.frequency.setValueAtTime(f0, start);111  osc.frequency.exponentialRampToValueAtTime(f1, start + dur);112  const g = ctx.createGain();113  g.gain.setValueAtTime(gain, start);114  g.gain.exponentialRampToValueAtTime(0.0001, start + dur);115  osc.connect(g).connect(bus);116  if (wet > 0) {117    const send = ctx.createGain();118    send.gain.value = wet;119    g.connect(send).connect(verb);120  }121  osc.start(start);122  osc.stop(start + dur + 0.05);123}124125export function shot({ silent, heavy, rail }) {126  if (rail) {127    // Capacitor discharge: a falling whine and a sharp crack.128    sweep({ type: 'sawtooth', f0: 2400, f1: 120, dur: 0.45, gain: 0.12, wet: 0.3 });129    burst({ freq: 6000, dur: 0.08, gain: 0.45, type: 'highpass', wet: 0.35 });130    burst({ freq: 180, dur: 0.6, gain: 0.8, wet: 0.45 });131    return;132  }133  if (silent) {134    burst({ freq: 700, dur: 0.12, gain: 0.2, wet: 0.05 });135    burst({ freq: 2200, dur: 0.03, gain: 0.06, type: 'bandpass', q: 3, wet: 0 });136    return;137  }138  burst({ freq: 1400, dur: 0.35, gain: heavy ? 1.0 : 0.8, wet: 0.35 });139  burst({ freq: 160, dur: heavy ? 0.7 : 0.45, gain: heavy ? 1.0 : 0.7, wet: 0.45 });140}141142// Bolt-action cycling: the bolt lifts, then slams home a moment later.143export function bolt(delay = 0) {144  burst({ freq: 1900, dur: 0.05, gain: 0.22, type: 'bandpass', q: 2, delay, wet: 0 });145  burst({ freq: 420, dur: 0.09, gain: 0.18, delay: delay + 0.04, wet: 0.05 });146}147148// A spent case hitting the ground.149export function casing(delay = 0) {150  burst({ freq: rand(3600, 5400), dur: 0.03, gain: 0.07, type: 'bandpass', q: 5, delay, wet: 0.12 });151}152153// Magazine release at the start of a reload.154export function reload() {155  burst({ freq: 900, dur: 0.06, gain: 0.3, type: 'bandpass', q: 3, wet: 0 });156}157158// Magazine seated when the reload finishes.159export function magIn() {160  burst({ freq: 1200, dur: 0.05, gain: 0.3, type: 'bandpass', q: 4, wet: 0.05 });161  burst({ freq: 300, dur: 0.12, gain: 0.35, delay: 0.06, wet: 0.1 });162}163164export function empty() {165  burst({ freq: 2000, dur: 0.04, gain: 0.2, type: 'bandpass', q: 6, wet: 0 });166}167168// A body dropping: low thump and a short, dull fall after it.169export function kill() {170  burst({ freq: 350, dur: 0.2, gain: 0.35, wet: 0.15 });171  burst({ freq: 140, dur: 0.22, gain: 0.4, delay: 0.12, wet: 0.2 });172}173174// Solid surface hit: brick, glass and steel all ring a little differently.175export function impact() {176  burst({ freq: rand(700, 1600), dur: 0.07, gain: 0.14, type: 'bandpass', q: 1.2, wet: 0.2 });177}178179// Bullet hitting a body: a wet thud, not a crack.180export function thud() {181  burst({ freq: 260, dur: 0.14, gain: 0.45, wet: 0.1 });182  burst({ freq: 1800, dur: 0.025, gain: 0.08, type: 'highpass', wet: 0 });183}184185// A zombie moaning. Louder when close, panned to where it is relative to you186// (pan: -1 left, 1 right). Rate-limited so a crowd does not turn into noise.187export function groan(dist, pan = 0, loud = 1) {188  if (!ctx) return;189  const now = ctx.currentTime;190  if (now - lastGroan < 0.5) return;191  lastGroan = now;192  const level = loud * 0.2 * Math.max(0.05, 1 - dist / 160);193  if (level < 0.005) return;194195  // Every moan gets its own length, pitch contour, vibrato and vowel.196  const dur = rand(0.9, 1.6);197  const peak = now + dur * rand(0.25, 0.5);198  const base = rand(80, 130);199  const osc = ctx.createOscillator();200  osc.type = 'sawtooth';201  osc.frequency.setValueAtTime(base * rand(0.7, 0.85), now);202  osc.frequency.linearRampToValueAtTime(base * rand(1.3, 1.55), peak);203  osc.frequency.linearRampToValueAtTime(base * rand(0.8, 1), now + dur);204205  // Vibrato that makes it sound throaty rather than like a synth tone.206  const lfo = ctx.createOscillator();207  lfo.frequency.value = rand(4, 7);208  const lfoAmt = ctx.createGain();209  lfoAmt.gain.value = base * rand(0.02, 0.07);210  lfo.connect(lfoAmt).connect(osc.frequency);211212  // Two band-passes in the vowel region so it reads as a voice. Their centres213  // are random, so one moan can sound like "oo" and the next like "ah".214  const vowel = ctx.createBiquadFilter();215  vowel.type = 'bandpass';216  vowel.frequency.value = rand(400, 650);217  vowel.Q.value = rand(1.8, 2.8);218  const formant = ctx.createBiquadFilter();219  formant.type = 'bandpass';220  formant.frequency.value = rand(900, 1400);221  formant.Q.value = 3;222  const formantAmt = ctx.createGain();223  formantAmt.gain.value = rand(0.2, 0.5);224225  const env = ctx.createGain();226  env.gain.setValueAtTime(0.0001, now);227  env.gain.exponentialRampToValueAtTime(level, now + 0.15 + dur * 0.1);228  env.gain.setValueAtTime(level * 0.8, now + dur * 0.55);229  env.gain.exponentialRampToValueAtTime(0.0001, now + dur);230231  const panner = ctx.createStereoPanner();232  panner.pan.value = Math.max(-1, Math.min(1, pan));233234  osc.connect(vowel).connect(env);235  osc.connect(formant).connect(formantAmt).connect(env);236  env.connect(panner).connect(bus);237  const send = ctx.createGain();238  send.gain.value = 0.25;239  panner.connect(send).connect(verb);240241  osc.start(now);242  lfo.start(now);243  osc.stop(now + dur + 0.1);244  lfo.stop(now + dur + 0.1);245}246247// Hot, close kill: a short grunt that sits in front of you.248export function deathMoan() {249  groan(0, 0, 1.4);250}251252function brownBuffer(seconds) {253  const len = Math.floor(ctx.sampleRate * seconds);254  const buf = ctx.createBuffer(1, len, ctx.sampleRate);255  const d = buf.getChannelData(0);256  // Brown noise, with fades at both ends so the loop point does not click.257  let last = 0;258  const fade = Math.floor(ctx.sampleRate * 0.25);259  for (let i = 0; i < len; i++) {260    last = (last + 0.02 * (Math.random() * 2 - 1)) / 1.02;261    const edge = Math.min(1, i / fade, (len - i) / fade);262    d[i] = last * 3.5 * edge;263  }264  return buf;265}266267// One wind layer. Its loop length and gust rate are set apart from the other268// layer's, so the combined sound takes a long time to line up with itself.269function windLayer(seconds, level, gustHz, toneHz) {270  const src = ctx.createBufferSource();271  src.buffer = brownBuffer(seconds);272  src.loop = true;273  const lp = ctx.createBiquadFilter();274  lp.type = 'lowpass';275  lp.frequency.value = 650;276  lp.Q.value = 0.5;277  const g = ctx.createGain();278  g.gain.value = level;279  src.connect(lp).connect(g).connect(bus);280281  // Gusts: slow swells in volume and in how much high end gets through.282  // Each starts at a random point in its cycle.283  const gust = ctx.createOscillator();284  gust.frequency.value = gustHz;285  const gustAmt = ctx.createGain();286  gustAmt.gain.value = level * 0.45;287  gust.connect(gustAmt).connect(g.gain);288  const tone = ctx.createOscillator();289  tone.frequency.value = toneHz;290  const toneAmt = ctx.createGain();291  toneAmt.gain.value = 220;292  tone.connect(toneAmt).connect(lp.frequency);293294  src.start();295  gust.start(ctx.currentTime + rand(0, 1 / gustHz));296  tone.start(ctx.currentTime + rand(0, 1 / toneHz));297}298299function startWind() {300  windLayer(11.3, 0.06, 0.06, 0.037);301  windLayer(7.7, 0.04, 0.047, 0.023);302}303304// Called every frame. Occasionally a car alarm goes off somewhere far away.305export function tickAmbient(dt) {306  if (!ctx) return;307  alarmT -= dt;308  if (alarmT > 0) return;309  alarmT = rand(50, 120);310  carAlarm();311}312313// A siren a long way off: quiet, dulled by distance, with echo and room sound314// and no direct edge. Pitch and length change a little each time.315function carAlarm() {316  const now = ctx.currentTime;317  const sweeps = Math.floor(rand(6, 9));318  const period = rand(0.38, 0.46);319  const total = sweeps * period;320  const lo = rand(760, 880);321  const hi = lo * rand(1.4, 1.6);322  const osc = ctx.createOscillator();323  osc.type = 'square';324  for (let i = 0; i < sweeps; i++) {325    const t = now + i * period;326    osc.frequency.setValueAtTime(lo, t);327    osc.frequency.linearRampToValueAtTime(hi, t + period * 0.95);328  }329  // Air soaks up the top end, so the lowpass sits well below the tone.330  const lp = ctx.createBiquadFilter();331  lp.type = 'lowpass';332  lp.frequency.value = 600;333  lp.Q.value = 0.8;334  const g = ctx.createGain();335  const level = 0.012;336  g.gain.setValueAtTime(0.0001, now);337  g.gain.exponentialRampToValueAtTime(level, now + 1.2);338  g.gain.setValueAtTime(level, now + total - 0.8);339  g.gain.exponentialRampToValueAtTime(0.0001, now + total);340  osc.connect(lp).connect(g);341  g.connect(bus);342  const room = ctx.createGain();343  room.gain.value = 1.1;344  g.connect(room).connect(verb);345  const echoSend = ctx.createGain();346  echoSend.gain.value = 0.7;347  g.connect(echoSend).connect(echo);348  osc.start(now);349  osc.stop(now + total + 0.05);350}