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

reorganised repo
author ark
date 2026-10-20 00:12 +0200
parents
children 85d23328a215
comparison
equal deleted inserted replaced
16:30bd10284fd8 17:fe680946164b
1 // sound: recorded sounds from data/sounds.js, placeholder beeps for events
2 // without a recording. the player's sound on or off choice is stored with
3 // MM.storage; the config's enabled setting applies until the first choice.
4
5 window.MM = window.MM || {};
6
7 MM.audio = (function () {
8 "use strict";
9
10 var cfg = MM.config.sound;
11 var ctx = null, master = null;
12 var buffers = {}; // event -> decoded recordings
13 var last = {}; // event -> audio clock time of its last play
14 var ends = {}; // event -> audio clock time when its sounds have ended
15 var started = false;
16 var on = MM.storage.get("sound", cfg.enabled);
17
18 // create the audio context and decode the recordings. the browser keeps
19 // the context suspended until unlock() runs in a user interaction.
20 function init() {
21 var AC = window.AudioContext || window.webkitAudioContext;
22 if (!AC) return;
23 ctx = new AC();
24 master = ctx.createGain();
25 master.gain.value = on ? cfg.volume : 0;
26 master.connect(ctx.destination);
27 var sounds = MM.sounds || {};
28 Object.keys(sounds).forEach(function (name) {
29 buffers[name] = [];
30 sounds[name].forEach(function (b64) { decode(name, b64); });
31 });
32 }
33
34 function decode(name, b64) {
35 var bin = atob(b64), bytes = new Uint8Array(bin.length);
36 for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
37 // the callback form, as older safari has no promise form
38 ctx.decodeAudioData(bytes.buffer,
39 function (buf) { buffers[name].push(buf); },
40 function () { console.error("sound not decoded:", name); });
41 }
42
43 // call from the play button's handler. sound stays off until then.
44 function start() {
45 started = true;
46 unlock();
47 }
48
49 // call from a pointer or touch handler: browsers start sound only there.
50 // does nothing before start().
51 function unlock() {
52 if (!ctx || !started || ctx.state === "running") return;
53 ctx.resume();
54 // older safari also needs a sound started in the handler
55 var src = ctx.createBufferSource();
56 src.buffer = ctx.createBuffer(1, 1, 22050);
57 src.connect(ctx.destination);
58 src.start(0);
59 }
60
61 // notes of [frequency, seconds] from when on, into out. returns the
62 // total length.
63 function beep(notes, out, when) {
64 var t = when;
65 notes.forEach(function (n) {
66 var osc = ctx.createOscillator(), env = ctx.createGain();
67 osc.type = cfg.beep_wave;
68 osc.frequency.value = n[0];
69 env.gain.setValueAtTime(1, t);
70 env.gain.exponentialRampToValueAtTime(0.001, t + n[1]);
71 osc.connect(env);
72 env.connect(out);
73 osc.start(t);
74 osc.stop(t + n[1]);
75 t += n[1];
76 });
77 return t - when;
78 }
79
80 // play a random recording of the event, or its beep if it has none.
81 // after lists events whose sounds still playing are let finish first.
82 // variants are picked with Math.random, so sound does not change the
83 // game's seeded random numbers.
84 function play(name, after) {
85 if (!on || !ctx || ctx.state !== "running") return;
86 var ev = cfg.event[name];
87 if (!ev) return;
88 var now = ctx.currentTime;
89 if (ev.min_interval && now - last[name] < ev.min_interval) return;
90 last[name] = now;
91 var when = now;
92 (after || []).forEach(function (a) {
93 if (ends[a] > when) when = ends[a];
94 });
95 var gain = ctx.createGain();
96 gain.gain.value = ev.volume;
97 gain.connect(master);
98 var list = buffers[name], length;
99 if (list && list.length) {
100 var src = ctx.createBufferSource();
101 src.buffer = list[Math.floor(Math.random() * list.length)];
102 src.connect(gain);
103 src.start(when);
104 length = src.buffer.duration;
105 } else if (ev.beep) {
106 length = beep(ev.beep, gain, when);
107 } else {
108 return;
109 }
110 ends[name] = Math.max(ends[name] || 0, when + length);
111 }
112
113 function enabled() {
114 return on;
115 }
116
117 // switch sound on or off and store the choice. sounds already playing
118 // are muted at once.
119 function toggle() {
120 on = !on;
121 if (master) master.gain.value = on ? cfg.volume : 0;
122 MM.storage.set("sound", on);
123 }
124
125 return { init: init, start: start, unlock: unlock, play: play, enabled: enabled, toggle: toggle };
126 })();