169 lines
5.9 KiB
TypeScript
169 lines
5.9 KiB
TypeScript
// Sound effects, synthesised with the Web Audio API: no sound files to
|
|
// load or license. Every sound is a few short notes or a filtered click
|
|
// shaped by an envelope. Settings live in this browser only.
|
|
|
|
export type Sound = 'place' | 'connect' | 'on' | 'off' | 'press' | 'delete' | 'tick' | 'solve' | 'fail' | 'unlock' | 'record' | 'error'
|
|
|
|
export interface SoundSettings {
|
|
on: boolean
|
|
/** 0 to 1. */
|
|
volume: number
|
|
/** A soft tick on every clock cycle, at speeds up to 8 Hz. */
|
|
ticks: boolean
|
|
}
|
|
|
|
const KEY = 'logigate:sound'
|
|
const DEFAULTS: SoundSettings = { on: true, volume: 0.6, ticks: false }
|
|
|
|
export function loadSoundSettings(): SoundSettings {
|
|
try {
|
|
const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}') as Partial<SoundSettings>
|
|
return {
|
|
on: typeof raw.on === 'boolean' ? raw.on : DEFAULTS.on,
|
|
volume: typeof raw.volume === 'number' && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
|
|
ticks: typeof raw.ticks === 'boolean' ? raw.ticks : DEFAULTS.ticks,
|
|
}
|
|
} catch {
|
|
return { ...DEFAULTS }
|
|
}
|
|
}
|
|
|
|
export function saveSoundSettings(s: SoundSettings) {
|
|
try {
|
|
localStorage.setItem(KEY, JSON.stringify(s))
|
|
} catch {}
|
|
}
|
|
|
|
let ctx: AudioContext | null = null
|
|
let master: GainNode | null = null
|
|
let noise: AudioBuffer | null = null
|
|
|
|
/** The audio graph, made on first use (browsers only allow it after a click or key). */
|
|
function audio(volume: number): { ctx: AudioContext; out: GainNode } | null {
|
|
if (typeof window === 'undefined' || !('AudioContext' in window)) return null
|
|
if (!ctx) {
|
|
ctx = new AudioContext()
|
|
master = ctx.createGain()
|
|
// A gentle limiter so overlapping sounds never clip.
|
|
const comp = ctx.createDynamicsCompressor()
|
|
comp.threshold.value = -12
|
|
comp.ratio.value = 6
|
|
master.connect(comp).connect(ctx.destination)
|
|
noise = ctx.createBuffer(1, ctx.sampleRate * 0.2, ctx.sampleRate)
|
|
const data = noise.getChannelData(0)
|
|
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1
|
|
}
|
|
if (ctx.state === 'suspended') void ctx.resume()
|
|
master!.gain.value = volume * volume * 0.5
|
|
return { ctx, out: master! }
|
|
}
|
|
|
|
interface Note {
|
|
/** Hz; with `to`, glides there over the note. */
|
|
f: number
|
|
to?: number
|
|
/** Start, seconds from now. */
|
|
at?: number
|
|
/** Length in seconds. */
|
|
len: number
|
|
type?: OscillatorType
|
|
gain?: number
|
|
}
|
|
|
|
function play(a: { ctx: AudioContext; out: GainNode }, n: Note) {
|
|
const t = a.ctx.currentTime + (n.at ?? 0)
|
|
const osc = a.ctx.createOscillator()
|
|
const env = a.ctx.createGain()
|
|
osc.type = n.type ?? 'sine'
|
|
osc.frequency.setValueAtTime(n.f, t)
|
|
if (n.to) osc.frequency.exponentialRampToValueAtTime(n.to, t + n.len)
|
|
const peak = n.gain ?? 0.3
|
|
env.gain.setValueAtTime(0.0001, t)
|
|
env.gain.exponentialRampToValueAtTime(peak, t + 0.006)
|
|
env.gain.exponentialRampToValueAtTime(0.0001, t + n.len)
|
|
osc.connect(env).connect(a.out)
|
|
osc.start(t)
|
|
osc.stop(t + n.len + 0.02)
|
|
}
|
|
|
|
/** A short burst of filtered noise: the mechanical part of a click. */
|
|
function click(a: { ctx: AudioContext; out: GainNode }, freq: number, len: number, gain: number, at = 0) {
|
|
const t = a.ctx.currentTime + at
|
|
const src = a.ctx.createBufferSource()
|
|
src.buffer = noise
|
|
const bp = a.ctx.createBiquadFilter()
|
|
bp.type = 'bandpass'
|
|
bp.frequency.value = freq
|
|
bp.Q.value = 2.5
|
|
const env = a.ctx.createGain()
|
|
env.gain.setValueAtTime(gain, t)
|
|
env.gain.exponentialRampToValueAtTime(0.0001, t + len)
|
|
src.connect(bp).connect(env).connect(a.out)
|
|
src.start(t)
|
|
src.stop(t + len + 0.02)
|
|
}
|
|
|
|
const NOTE = (semitones: number) => 440 * 2 ** ((semitones - 9) / 12) // 0 = C4
|
|
|
|
function render(a: { ctx: AudioContext; out: GainNode }, s: Sound) {
|
|
switch (s) {
|
|
case 'place':
|
|
play(a, { f: 260, to: 150, len: 0.09, gain: 0.35 })
|
|
click(a, 1800, 0.03, 0.25)
|
|
break
|
|
case 'connect':
|
|
click(a, 3200, 0.02, 0.2)
|
|
play(a, { f: NOTE(19), len: 0.06, type: 'triangle', gain: 0.18 })
|
|
play(a, { f: NOTE(26), at: 0.045, len: 0.08, type: 'triangle', gain: 0.16 })
|
|
break
|
|
case 'on':
|
|
click(a, 2600, 0.025, 0.35)
|
|
play(a, { f: NOTE(24), len: 0.05, type: 'triangle', gain: 0.12 })
|
|
break
|
|
case 'off':
|
|
click(a, 1500, 0.025, 0.3)
|
|
play(a, { f: NOTE(17), len: 0.05, type: 'triangle', gain: 0.1 })
|
|
break
|
|
case 'press':
|
|
click(a, 900, 0.04, 0.35)
|
|
break
|
|
case 'delete':
|
|
play(a, { f: 420, to: 160, len: 0.12, type: 'triangle', gain: 0.22 })
|
|
click(a, 700, 0.06, 0.15)
|
|
break
|
|
case 'tick':
|
|
click(a, 5200, 0.012, 0.08)
|
|
break
|
|
case 'error':
|
|
play(a, { f: 150, len: 0.09, type: 'square', gain: 0.08 })
|
|
play(a, { f: 140, at: 0.1, len: 0.12, type: 'square', gain: 0.08 })
|
|
break
|
|
case 'fail':
|
|
play(a, { f: NOTE(4), len: 0.14, type: 'triangle', gain: 0.25 })
|
|
play(a, { f: NOTE(1), at: 0.15, len: 0.28, type: 'triangle', gain: 0.25 })
|
|
break
|
|
case 'solve':
|
|
;[0, 4, 7, 12].forEach((n, i) => play(a, { f: NOTE(12 + n), at: i * 0.075, len: 0.32, type: 'triangle', gain: 0.22 }))
|
|
play(a, { f: NOTE(24), at: 0.3, len: 0.6, gain: 0.12 })
|
|
break
|
|
case 'unlock':
|
|
;[0, 7, 12, 16, 19, 24].forEach((n, i) => play(a, { f: NOTE(19 + n), at: 0.35 + i * 0.045, len: 0.25, gain: 0.1 }))
|
|
break
|
|
case 'record':
|
|
;[[7, 0], [12, 0.11], [16, 0.22], [19, 0.33]].forEach(([n, at]) => play(a, { f: NOTE(n!), at, len: 0.3, type: 'square', gain: 0.07 }))
|
|
;[0, 4, 7].forEach(n => play(a, { f: NOTE(12 + n), at: 0.45, len: 0.9, type: 'triangle', gain: 0.16 }))
|
|
break
|
|
}
|
|
}
|
|
|
|
/** Plays a sound if sound is on. Cheap to call often: rapid repeats of the same sound are thinned out. */
|
|
const lastAt = new Map<Sound, number>()
|
|
export function sfx(s: Sound, settings: SoundSettings) {
|
|
if (!settings.on || settings.volume <= 0) return
|
|
const now = performance.now()
|
|
if (now - (lastAt.get(s) ?? 0) < (s === 'tick' ? 40 : 25)) return
|
|
lastAt.set(s, now)
|
|
const a = audio(settings.volume)
|
|
if (a) render(a, s)
|
|
}
|