comparison game/js/audio.js @ 6:910b26feca76

full game flow
author ark
date 2026-10-19 01:05 +0200
parents 2d46729a022e
children 2c4fed8baed9
comparison
equal deleted inserted replaced
5:67bf3c505145 6:910b26feca76
9 var cfg = MM.config.sound; 9 var cfg = MM.config.sound;
10 var ctx = null, master = null; 10 var ctx = null, master = null;
11 var buffers = {}; // event -> decoded recordings 11 var buffers = {}; // event -> decoded recordings
12 var last = {}; // event -> audio clock time of its last play 12 var last = {}; // event -> audio clock time of its last play
13 var ends = {}; // event -> audio clock time when its sounds have ended 13 var ends = {}; // event -> audio clock time when its sounds have ended
14 var started = false;
14 15
15 // create the audio context and decode the recordings. the browser keeps 16 // create the audio context and decode the recordings. the browser keeps
16 // the context suspended until unlock() runs in a user interaction. 17 // the context suspended until unlock() runs in a user interaction.
17 function init() { 18 function init() {
18 var AC = window.AudioContext || window.webkitAudioContext; 19 var AC = window.AudioContext || window.webkitAudioContext;
35 ctx.decodeAudioData(bytes.buffer, 36 ctx.decodeAudioData(bytes.buffer,
36 function (buf) { buffers[name].push(buf); }, 37 function (buf) { buffers[name].push(buf); },
37 function () { console.error("sound not decoded:", name); }); 38 function () { console.error("sound not decoded:", name); });
38 } 39 }
39 40
40 // call from a pointer or touch handler: browsers start sound only there 41 // call from the play button's handler. sound stays off until then.
42 function start() {
43 started = true;
44 unlock();
45 }
46
47 // call from a pointer or touch handler: browsers start sound only there.
48 // does nothing before start().
41 function unlock() { 49 function unlock() {
42 if (!ctx || ctx.state === "running") return; 50 if (!ctx || !started || ctx.state === "running") return;
43 ctx.resume(); 51 ctx.resume();
44 // older safari also needs a sound started in the handler 52 // older safari also needs a sound started in the handler
45 var src = ctx.createBufferSource(); 53 var src = ctx.createBufferSource();
46 src.buffer = ctx.createBuffer(1, 1, 22050); 54 src.buffer = ctx.createBuffer(1, 1, 22050);
47 src.connect(ctx.destination); 55 src.connect(ctx.destination);
98 return; 106 return;
99 } 107 }
100 ends[name] = Math.max(ends[name] || 0, when + length); 108 ends[name] = Math.max(ends[name] || 0, when + length);
101 } 109 }
102 110
103 return { init: init, unlock: unlock, play: play }; 111 return { init: init, start: start, unlock: unlock, play: play };
104 })(); 112 })();