Skip to content

gitflarePublicPartly agent-ready40

sketch-rush

Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.

Add the Apache-2.0 licencedbe1e99
JavaScript57 lines2.5 KB
// [freq, duration, wave, volume, delay]const SOUNDS = {  tick: [[1200, 0.04, "square", 0.05]],  correct: [[660, 0.12, "sine", 0.2], [880, 0.12, "sine", 0.2, 0.11], [1320, 0.22, "sine", 0.2, 0.22]],  close: [[300, 0.12, "triangle", 0.18], [260, 0.16, "triangle", 0.18, 0.1]],  turn: [[440, 0.1, "square", 0.1], [660, 0.18, "square", 0.1, 0.1]],  reveal: [[520, 0.15, "sawtooth", 0.1], [390, 0.3, "sawtooth", 0.1, 0.14]],  win: [[523, 0.15, "triangle", 0.2], [659, 0.15, "triangle", 0.2, 0.15], [784, 0.15, "triangle", 0.2, 0.3], [1047, 0.4, "triangle", 0.2, 0.45]],  pop: [[900, 0.05, "sine", 0.12]],};export const SOUND_NAMES = Object.keys(SOUNDS); export function createAudio() {  let ac = null, muted = false, ng = null, ns = null, nf = null;  const startScratch = () => {    if (ns || !ac) return;    const len = ac.sampleRate | 0, buf = ac.createBuffer(1, len, ac.sampleRate), d = buf.getChannelData(0);    for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;    ns = ac.createBufferSource(); ns.buffer = buf; ns.loop = true;    nf = ac.createBiquadFilter(); nf.type = "bandpass"; nf.frequency.value = 3000; nf.Q.value = 0.8;    ng = ac.createGain(); ng.gain.value = 0;    ns.connect(nf); nf.connect(ng); ng.connect(ac.destination); ns.start();  };  return {    setMuted(m) { muted = !!m; if (ng && muted) ng.gain.value = 0; },    isMuted() { return muted; },    /** speed in board units/ms; 0 = idle */    scratch(speed) {      if (!ac || muted) return;      startScratch();      const v = Math.min(0.09, (speed || 0) * 0.05);      ng.gain.setTargetAtTime(v, ac.currentTime, 0.03);      nf.frequency.setTargetAtTime(2200 + Math.min(2500, speed * 1500), ac.currentTime, 0.03);    },    unlock() {      try {        if (!ac) { const C = globalThis.AudioContext || globalThis.webkitAudioContext; if (C) ac = new C(); }        if (ac && ac.state === "suspended") ac.resume();      } catch {}    },    play(name) {      const def = SOUNDS[name];      if (!ac || !def || muted) return;      const now = ac.currentTime;      for (const [f, d, type, vol, delay = 0] of def) {        const o = ac.createOscillator(), g = ac.createGain();        o.type = type; o.frequency.value = f;        g.gain.setValueAtTime(0.0001, now + delay);        g.gain.exponentialRampToValueAtTime(vol, now + delay + 0.01);        g.gain.exponentialRampToValueAtTime(0.0001, now + delay + d);        o.connect(g); g.connect(ac.destination);        o.start(now + delay); o.stop(now + delay + d + 0.02);      }    },  };}