view game/js/audio.js @ 33:767970d80214

Added tag 0.10.0 for changeset 85d23328a215
author ark
date 2026-10-20 18:39 +0200
parents 85d23328a215
children
line wrap: on
line source

// sound: recorded sounds from data/sounds.js, placeholder beeps for events
// without a recording, and looping music for the splash screen. 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;
    // the looping music: {name, src, gain}, src null while its recording is
    // still being decoded
    var music = null;
    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);
                if (music && music.name === name && !music.src) startMusic();
            },
            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);
    }

    // play the event's first recording in a loop until stopMusic(). does
    // nothing while sound is off. on a context not yet unlocked, the music
    // starts with the unlock; before its recording is decoded, once it is.
    function playMusic(name) {
        if (!on || !ctx || music || !cfg.event[name]) return;
        music = { name: name, src: null, gain: null };
        if (buffers[name] && buffers[name].length) startMusic();
    }

    function startMusic() {
        music.gain = ctx.createGain();
        music.gain.gain.value = cfg.event[music.name].volume;
        music.gain.connect(master);
        music.src = ctx.createBufferSource();
        music.src.buffer = buffers[music.name][0];
        music.src.loop = true;
        music.src.connect(music.gain);
        music.src.start(ctx.currentTime);
    }

    // fade the music out over the music_fade setting and stop it
    function stopMusic() {
        if (!music) return;
        if (music.src) {
            var now = ctx.currentTime;
            music.gain.gain.setValueAtTime(music.gain.gain.value, now);
            music.gain.gain.linearRampToValueAtTime(0, now + cfg.music_fade);
            music.src.stop(now + cfg.music_fade);
        }
        music = null;
    }

    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, playMusic: playMusic,
             stopMusic: stopMusic, enabled: enabled, toggle: toggle };
})();