xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / web / js / sound.js 71 lines2.5 kB Raw
1const VOICES = {
2  click: [['triangle', 660, 520, 0.05, 0.12]],
3  step: [['noise', 900, 300, 0.05, 0.05]],
4  hit: [['noise', 1800, 200, 0.12, 0.22], ['square', 140, 60, 0.1, 0.12]],
5  crit: [['noise', 2600, 200, 0.18, 0.3], ['square', 220, 50, 0.2, 0.18]],
6  heal: [['sine', 520, 880, 0.25, 0.14]],
7  fall: [['sawtooth', 220, 55, 0.4, 0.14]],
8  threat: [['triangle', 196, 196, 0.35, 0.12], ['triangle', 233, 233, 0.35, 0.08]],
9  coin: [['square', 988, 988, 0.06, 0.08], ['square', 1319, 1319, 0.12, 0.08, 0.06]],
10  loot: [['triangle', 660, 990, 0.18, 0.12]],
11  rest: [['sine', 392, 392, 0.5, 0.1], ['sine', 494, 494, 0.5, 0.08, 0.12], ['sine', 587, 587, 0.6, 0.08, 0.24]],
12  win: [['triangle', 523, 523, 0.18, 0.14], ['triangle', 659, 659, 0.18, 0.14, 0.14], ['triangle', 784, 784, 0.4, 0.14, 0.28]],
13  level: [['sine', 523, 1047, 0.3, 0.12], ['sine', 784, 1568, 0.4, 0.1, 0.15]],
14  lose: [['triangle', 392, 392, 0.25, 0.14], ['triangle', 311, 311, 0.25, 0.14, 0.2], ['triangle', 262, 262, 0.5, 0.14, 0.4]],
15};
16
17export function createSound() {
18  let ctx = null;
19  let out = null;
20  let noise = null;
21  let muted = false;
22
23  function wake() {
24    if (ctx) return ctx.state === 'suspended' && ctx.resume();
25    ctx = new AudioContext();
26    out = ctx.createGain();
27    out.gain.value = 0.5;
28    out.connect(ctx.destination);
29    noise = ctx.createBuffer(1, ctx.sampleRate / 2, ctx.sampleRate);
30    const d = noise.getChannelData(0);
31    for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
32  }
33
34  function voice([type, f0, f1, dur, vol, delay = 0]) {
35    const t = ctx.currentTime + delay;
36    const g = ctx.createGain();
37    g.gain.setValueAtTime(vol, t);
38    g.gain.exponentialRampToValueAtTime(0.001, t + dur);
39    g.connect(out);
40    let src;
41    if (type === 'noise') {
42      src = ctx.createBufferSource();
43      src.buffer = noise;
44      const bp = ctx.createBiquadFilter();
45      bp.type = 'bandpass';
46      bp.frequency.setValueAtTime(f0, t);
47      bp.frequency.exponentialRampToValueAtTime(f1, t + dur);
48      src.connect(bp).connect(g);
49    } else {
50      src = ctx.createOscillator();
51      src.type = type;
52      src.frequency.setValueAtTime(f0, t);
53      src.frequency.exponentialRampToValueAtTime(f1, t + dur);
54      src.connect(g);
55    }
56    src.start(t);
57    src.stop(t + dur + 0.02);
58  }
59
60  return {
61    wake,
62    play(name) {
63      if (muted || !ctx || ctx.state !== 'running') return;
64      VOICES[name]?.forEach(voice);
65    },
66    toggle() {
67      muted = !muted;
68      return muted;
69    },
70  };
71}