diff game/js/audio.js @ 17:fe680946164b

reorganised repo
author ark
date 2026-10-20 00:12 +0200
parents
children 85d23328a215
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/audio.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,126 @@
+// sound: recorded sounds from data/sounds.js, placeholder beeps for events
+// without a recording. the player's sound on or off choice is stored with
+// MM.storage; the config's enabled setting applies until the first choice.
+
+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
+    var started = false;
+    var on = MM.storage.get("sound", cfg.enabled);
+
+    // 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) return;
+        ctx = new AC();
+        master = ctx.createGain();
+        master.gain.value = on ? cfg.volume : 0;
+        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 the play button's handler. sound stays off until then.
+    function start() {
+        started = true;
+        unlock();
+    }
+
+    // call from a pointer or touch handler: browsers start sound only there.
+    // does nothing before start().
+    function unlock() {
+        if (!ctx || !started || 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 (!on || !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);
+    }
+
+    function enabled() {
+        return on;
+    }
+
+    // switch sound on or off and store the choice. sounds already playing
+    // are muted at once.
+    function toggle() {
+        on = !on;
+        if (master) master.gain.value = on ? cfg.volume : 0;
+        MM.storage.set("sound", on);
+    }
+
+    return { init: init, start: start, unlock: unlock, play: play, enabled: enabled, toggle: toggle };
+})();