diff game/js/audio.js @ 4:2d46729a022e

sound processing and in-game sounds
author ark
date 2026-10-18 20:58 +0200
parents
children 910b26feca76
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/audio.js	Sun Oct 18 20:58:33 2026 +0200
@@ -0,0 +1,104 @@
+// sound: recorded sounds from data/sounds.js, placeholder beeps for events
+// without a recording
+
+window.MM = window.MM || {};
+
+MM.audio = (function () {
+    "use strict";
+
+    var cfg = MM.config.sound;
+    var ctx = null, master = null;
+    var buffers = {};   // event -> decoded recordings
+    var last = {};      // event -> audio clock time of its last play
+    var ends = {};      // event -> audio clock time when its sounds have ended
+
+    // create the audio context and decode the recordings. the browser keeps
+    // the context suspended until unlock() runs in a user interaction.
+    function init() {
+        var AC = window.AudioContext || window.webkitAudioContext;
+        if (!AC || !cfg.enabled) return;
+        ctx = new AC();
+        master = ctx.createGain();
+        master.gain.value = cfg.volume;
+        master.connect(ctx.destination);
+        var sounds = MM.sounds || {};
+        Object.keys(sounds).forEach(function (name) {
+            buffers[name] = [];
+            sounds[name].forEach(function (b64) { decode(name, b64); });
+        });
+    }
+
+    function decode(name, b64) {
+        var bin = atob(b64), bytes = new Uint8Array(bin.length);
+        for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+        // the callback form, as older safari has no promise form
+        ctx.decodeAudioData(bytes.buffer,
+            function (buf) { buffers[name].push(buf); },
+            function () { console.error("sound not decoded:", name); });
+    }
+
+    // call from a pointer or touch handler: browsers start sound only there
+    function unlock() {
+        if (!ctx || ctx.state === "running") return;
+        ctx.resume();
+        // older safari also needs a sound started in the handler
+        var src = ctx.createBufferSource();
+        src.buffer = ctx.createBuffer(1, 1, 22050);
+        src.connect(ctx.destination);
+        src.start(0);
+    }
+
+    // notes of [frequency, seconds] from when on, into out. returns the
+    // total length.
+    function beep(notes, out, when) {
+        var t = when;
+        notes.forEach(function (n) {
+            var osc = ctx.createOscillator(), env = ctx.createGain();
+            osc.type = cfg.beep_wave;
+            osc.frequency.value = n[0];
+            env.gain.setValueAtTime(1, t);
+            env.gain.exponentialRampToValueAtTime(0.001, t + n[1]);
+            osc.connect(env);
+            env.connect(out);
+            osc.start(t);
+            osc.stop(t + n[1]);
+            t += n[1];
+        });
+        return t - when;
+    }
+
+    // play a random recording of the event, or its beep if it has none.
+    // after lists events whose sounds still playing are let finish first.
+    // variants are picked with Math.random, so sound does not change the
+    // game's seeded random numbers.
+    function play(name, after) {
+        if (!ctx || ctx.state !== "running") return;
+        var ev = cfg.event[name];
+        if (!ev) return;
+        var now = ctx.currentTime;
+        if (ev.min_interval && now - last[name] < ev.min_interval) return;
+        last[name] = now;
+        var when = now;
+        (after || []).forEach(function (a) {
+            if (ends[a] > when) when = ends[a];
+        });
+        var gain = ctx.createGain();
+        gain.gain.value = ev.volume;
+        gain.connect(master);
+        var list = buffers[name], length;
+        if (list && list.length) {
+            var src = ctx.createBufferSource();
+            src.buffer = list[Math.floor(Math.random() * list.length)];
+            src.connect(gain);
+            src.start(when);
+            length = src.buffer.duration;
+        } else if (ev.beep) {
+            length = beep(ev.beep, gain, when);
+        } else {
+            return;
+        }
+        ends[name] = Math.max(ends[name] || 0, when + length);
+    }
+
+    return { init: init, unlock: unlock, play: play };
+})();