Add timed one-shot audio cues with hover-car flyby sounds
- New `Cue` type and `CueTrack` engine class: schedules one-shot effects at fixed meditation times via Web Audio, staying in sync across pause, seek, and skip (resume partway into a sounding cue). - Cyberpunk City now plays a random `fx-flyby-1..5.mp3` whoosh whenever a hover car passes close under the drone; the crossing moments are computed from the traffic lanes (`PASSES`) so the sound's midpoint lands as the car crosses the frame edge. - Wire `CueTrack` into the Player soundtrack alongside music and ambience, and document the new `cues` option in the README.
This commit is contained in:
parent
5e19f6e08e
commit
166dae262c
|
|
@ -57,6 +57,10 @@ Audio lives in `public/audio/` and is configured per meditation in its `index.ts
|
|||
`fx-waves.mp3`; its wave crashes are timed to the peaks listed in `mediterranean-coast/waves.ts`
|
||||
(re-measure them if the file changes).
|
||||
- `ambience: [{ … }, { … }]` — a list layers several loops at once (Cyberpunk City plays `fx-rain.mp3` and `fx-city.mp3` together).
|
||||
- `cues: [{ t, src, volume, pan }]` — one-shot sound effects starting at scene time `t`, also kept in sync after pause and skip.
|
||||
Cyberpunk City plays a random `fx-flyby-1…5.mp3` whenever a hover car passes close under the drone, timed so the middle of
|
||||
the file (`FLYBY_MID` in its `index.ts`) lands as the car crosses the bottom edge of the frame; the crossings are worked out
|
||||
from the traffic in `cyberpunk-city/traffic.ts` (`PASSES`).
|
||||
|
||||
With Docker, rebuild the `web` image (`docker compose up --build -d`) after adding audio so it's included.
|
||||
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,3 +1,5 @@
|
|||
import type { Cue } from '../meditations/types';
|
||||
|
||||
/**
|
||||
* Optional background music for a meditation. Fades in at the start and out at the end,
|
||||
* and does nothing at all when no track is configured.
|
||||
|
|
@ -162,3 +164,133 @@ export class AmbientLoop {
|
|||
src.node.stop(now + fade + 0.01);
|
||||
}
|
||||
}
|
||||
|
||||
/** How far ahead of the clock cues are handed to Web Audio, so they start exactly on time. */
|
||||
const CUE_LOOKAHEAD = 0.25;
|
||||
|
||||
/**
|
||||
* One-shot sound effects at fixed meditation times (Web Audio). Like AmbientLoop it follows the
|
||||
* meditation clock: a seek or resume lands partway into any cue that is still sounding.
|
||||
*/
|
||||
export class CueTrack {
|
||||
private ctx?: AudioContext;
|
||||
private master?: GainNode;
|
||||
private readonly cues: readonly Cue[];
|
||||
private readonly buffers = new Map<string, AudioBuffer>();
|
||||
private loading?: Promise<void>;
|
||||
private readonly live = new Set<{ node: AudioBufferSourceNode; gain: GainNode }>();
|
||||
/** Index of the first cue not yet scheduled. */
|
||||
private next = 0;
|
||||
private playing = false;
|
||||
private lastT = 0;
|
||||
|
||||
constructor(
|
||||
cues: readonly Cue[] = [],
|
||||
private readonly fadeIn = 4,
|
||||
private readonly fadeOut = 10,
|
||||
) {
|
||||
this.cues = [...cues].sort((a, b) => a.t - b.t);
|
||||
}
|
||||
|
||||
/** Must first be called from a user gesture so the AudioContext may start. */
|
||||
start(t: number): void {
|
||||
if (!this.cues.length) return;
|
||||
this.lastT = t;
|
||||
this.playing = true;
|
||||
if (!this.ctx) {
|
||||
this.ctx = new AudioContext();
|
||||
this.master = this.ctx.createGain();
|
||||
this.master.gain.value = 0;
|
||||
this.master.connect(this.ctx.destination);
|
||||
}
|
||||
void this.ctx.resume();
|
||||
void this.load().then(() => this.playing && this.restart(this.lastT));
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.playing = false;
|
||||
this.stopAll();
|
||||
}
|
||||
|
||||
seek(t: number): void {
|
||||
this.lastT = t;
|
||||
if (this.playing && this.buffers.size) this.restart(t);
|
||||
}
|
||||
|
||||
/** Call every frame with the meditation clock: applies fades and schedules upcoming cues. */
|
||||
update(t: number, duration: number): void {
|
||||
this.lastT = t;
|
||||
if (!this.ctx || !this.master) return;
|
||||
const k = Math.max(0, Math.min(1, t / this.fadeIn, (duration - t) / this.fadeOut));
|
||||
this.master.gain.setTargetAtTime(k, this.ctx.currentTime, 0.1);
|
||||
if (this.playing && this.buffers.size) this.schedule(t);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.pause();
|
||||
void this.ctx?.close();
|
||||
this.ctx = undefined;
|
||||
}
|
||||
|
||||
private load(): Promise<void> {
|
||||
const srcs = [...new Set(this.cues.map((c) => c.src))];
|
||||
this.loading ??= Promise.all(
|
||||
srcs.map((src) =>
|
||||
fetch(src)
|
||||
.then((r) => r.arrayBuffer())
|
||||
.then((data) => this.ctx!.decodeAudioData(data))
|
||||
.then((buf) => void this.buffers.set(src, buf))
|
||||
.catch(() => {
|
||||
/* missing or undecodable file — that cue just stays silent */
|
||||
}),
|
||||
),
|
||||
).then(() => {});
|
||||
return this.loading;
|
||||
}
|
||||
|
||||
private restart(t: number): void {
|
||||
this.stopAll(0.04);
|
||||
this.next = 0;
|
||||
this.schedule(t);
|
||||
}
|
||||
|
||||
/** Hand Web Audio every cue starting before t + lookahead, skipping any already over. */
|
||||
private schedule(t: number): void {
|
||||
while (this.next < this.cues.length && this.cues[this.next].t < t + CUE_LOOKAHEAD) {
|
||||
const cue = this.cues[this.next++];
|
||||
const buf = this.buffers.get(cue.src);
|
||||
if (buf && cue.t + buf.duration > t) this.play(cue, buf, cue.t - t);
|
||||
}
|
||||
}
|
||||
|
||||
/** Start a cue `delay` seconds from now, or partway in when the delay is negative. */
|
||||
private play(cue: Cue, buf: AudioBuffer, delay: number): void {
|
||||
const ctx = this.ctx!;
|
||||
const now = ctx.currentTime;
|
||||
const gain = ctx.createGain();
|
||||
gain.gain.value = cue.volume ?? 1;
|
||||
if (cue.pan) {
|
||||
const pan = ctx.createStereoPanner();
|
||||
pan.pan.value = cue.pan;
|
||||
gain.connect(pan).connect(this.master!);
|
||||
} else gain.connect(this.master!);
|
||||
const node = ctx.createBufferSource();
|
||||
node.buffer = buf;
|
||||
node.connect(gain);
|
||||
const voice = { node, gain };
|
||||
this.live.add(voice);
|
||||
node.onended = () => this.live.delete(voice);
|
||||
node.start(now + Math.max(0, delay), Math.max(0, -delay));
|
||||
}
|
||||
|
||||
private stopAll(fade = 0.04): void {
|
||||
if (!this.ctx) return;
|
||||
const now = this.ctx.currentTime;
|
||||
for (const { node, gain } of this.live) {
|
||||
gain.gain.setValueAtTime(gain.gain.value, now);
|
||||
gain.gain.linearRampToValueAtTime(0, now + fade);
|
||||
node.stop(now + fade + 0.01);
|
||||
}
|
||||
this.live.clear();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { Meditation, Scene } from '../types';
|
||||
import { Rng } from '../../engine/rng';
|
||||
import type { Cue, Meditation, Scene } from '../types';
|
||||
import { drawAirship } from './airship';
|
||||
import { compositeReflections, drawBuildings, traceReflections } from './buildings';
|
||||
import { drawCrowds } from './crowds';
|
||||
|
|
@ -8,7 +9,7 @@ import { drawRain } from './rain';
|
|||
import { clearFrame, drawSky } from './sky';
|
||||
import { drawGround, drawStalls, drawSteam } from './street';
|
||||
import { DURATION, frameAt } from './timeline';
|
||||
import { drawTraffic, traceTrafficReflections } from './traffic';
|
||||
import { drawTraffic, PASSES, traceTrafficReflections } from './traffic';
|
||||
|
||||
const scene: Scene = {
|
||||
render(s, t) {
|
||||
|
|
@ -32,6 +33,28 @@ const scene: Scene = {
|
|||
},
|
||||
};
|
||||
|
||||
/** The fx-flyby-N.mp3 files, and their midpoint (s), which lands as the car crosses the bottom of the frame. */
|
||||
const FLYBY_FILES = 5;
|
||||
const FLYBY_MID = 2.5;
|
||||
|
||||
/** A whoosh for each hover car that passes close, picked at random but never the same one twice running. */
|
||||
const FLYBYS: Cue[] = (() => {
|
||||
const r = new Rng(808);
|
||||
const out: Cue[] = [];
|
||||
let last = -1;
|
||||
let prevT = -Infinity;
|
||||
for (const p of PASSES) {
|
||||
// Skip the first seconds, still fading in, and let two cars passing together share one sound.
|
||||
if (p.t < 3 || p.t - prevT < 2.5) continue;
|
||||
let n = r.int(0, FLYBY_FILES - 2);
|
||||
if (n >= last) n++;
|
||||
last = n;
|
||||
prevT = p.t;
|
||||
out.push({ t: p.t - FLYBY_MID, src: `audio/fx-flyby-${n + 1}.mp3`, volume: 0.55 * Math.min(1, 10 / p.dist), pan: 0.35 * Math.sign(p.x) });
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
export const cyberpunkCity: Meditation = {
|
||||
id: 'cyberpunk-city',
|
||||
title: 'Cyberpunk City',
|
||||
|
|
@ -43,6 +66,7 @@ export const cyberpunkCity: Meditation = {
|
|||
{ src: 'audio/fx-rain.mp3', volume: 0.5 },
|
||||
{ src: 'audio/fx-city.mp3', volume: 0.4 },
|
||||
],
|
||||
cues: FLYBYS,
|
||||
duration: DURATION,
|
||||
previewTime: 282,
|
||||
createScene: () => scene,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { hex, mix, scale, type RGB } from '../../engine/color';
|
|||
import { hash, Rng } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { MIRROR } from './buildings';
|
||||
import { camZAt, DURATION, TIMES } from './drone';
|
||||
import { altitudeAt, camZAt, DURATION, TIMES } from './drone';
|
||||
import { CYAN, ICE, PINK, RED, VIOLET } from './neon';
|
||||
import { glowDot } from './street';
|
||||
import { haze, type Frame } from './timeline';
|
||||
|
|
@ -16,6 +16,7 @@ import {
|
|||
glowClarity,
|
||||
GREEN,
|
||||
H,
|
||||
HORIZON,
|
||||
LAST_CROSS,
|
||||
LINE,
|
||||
MAT,
|
||||
|
|
@ -276,13 +277,22 @@ function crossCars(t: number, out: Placed[]): void {
|
|||
}
|
||||
}
|
||||
|
||||
/** Where car i of an air lane is along the avenue at time t (lanes wrap around). */
|
||||
function laneZ(ln: AirLane, i: number, t: number): number {
|
||||
const off = (i + hash(i, ln.seed, 122) * 0.6) * (AIR_LEN / ln.n);
|
||||
return AIR_LOW + ((((off + t * ln.speed * ln.dir) % AIR_LEN) + AIR_LEN) % AIR_LEN);
|
||||
}
|
||||
|
||||
const FLYBY_X = 2.2;
|
||||
const FLYBY_Y = 35;
|
||||
const flybyZ = (t: number): number => camZAt(TIMES.flyby) - 28 + 8.5 * (t - TIMES.flyby);
|
||||
|
||||
function placeAir(f: Frame): Placed[] {
|
||||
const out: Placed[] = [];
|
||||
const cam = f.cam;
|
||||
for (const ln of AIR_LANES) {
|
||||
for (let i = 0; i < ln.n; i++) {
|
||||
const off = (i + hash(i, ln.seed, 122) * 0.6) * (AIR_LEN / ln.n);
|
||||
const z = AIR_LOW + ((((off + f.t * ln.speed * ln.dir) % AIR_LEN) + AIR_LEN) % AIR_LEN);
|
||||
const z = laneZ(ln, i, f.t);
|
||||
if (z < cam.z + 2 || z - cam.z > 900) continue;
|
||||
const bob = 0.4 * Math.sin(f.t * 0.6 + i * 1.7);
|
||||
out.push(airCar(ln.x + 0.6 * Math.sin(i * 2.3), ln.y + bob, z, AIR_LOOKS[(i + ln.seed) % AIR_LOOKS.length], ln.dir));
|
||||
|
|
@ -291,12 +301,51 @@ function placeAir(f: Frame): Placed[] {
|
|||
crossCars(f.t, out);
|
||||
// One hover car rises from under the drone and glides on ahead up the avenue.
|
||||
if (f.t > TIMES.flyby) {
|
||||
const z = camZAt(TIMES.flyby) - 28 + 8.5 * (f.t - TIMES.flyby);
|
||||
if (z > cam.z + 2 && z < 1200) out.push(airCar(2.2, 35 + 0.3 * Math.sin(f.t * 0.7), z, AIR_LOOKS[1], 1));
|
||||
const z = flybyZ(f.t);
|
||||
if (z > cam.z + 2 && z < 1200) out.push(airCar(FLYBY_X, FLYBY_Y + 0.3 * Math.sin(f.t * 0.7), z, AIR_LOOKS[1], 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hover car flying close under the drone: when it crosses the bottom edge of the frame (coming into
|
||||
* view or leaving it), which side it's on, and how near it gets (m).
|
||||
*/
|
||||
export interface Pass {
|
||||
t: number;
|
||||
x: number;
|
||||
dist: number;
|
||||
}
|
||||
|
||||
/** Cars closer than this as they pass count as flying by; it takes in the lanes below the drone. */
|
||||
const PASS_NEAR = 18;
|
||||
|
||||
/** Every close pass over the journey, in time order. */
|
||||
export const PASSES: readonly Pass[] = (() => {
|
||||
const out: Pass[] = [];
|
||||
const scan = (x: number, y: number, z: (t: number) => number, from: number) => {
|
||||
// How far ahead of the drone the car is, less the distance where it meets the bottom edge.
|
||||
const past = (t: number) => {
|
||||
const drop = altitudeAt(t) - y - climb(z(t));
|
||||
return z(t) - camZAt(t) - (drop * F) / (H - HORIZON);
|
||||
};
|
||||
let prev = past(from);
|
||||
for (let n = 1; from + n * 0.05 <= DURATION; n++) {
|
||||
const t = from + n * 0.05;
|
||||
const cur = past(t);
|
||||
// At the edge, and not just a lane wrapping around.
|
||||
if (cur * prev <= 0 && Math.abs(cur - prev) < 5) {
|
||||
const dist = Math.hypot(x, y - altitudeAt(t));
|
||||
if (y < altitudeAt(t) && dist < PASS_NEAR) out.push({ t, x, dist });
|
||||
}
|
||||
prev = cur;
|
||||
}
|
||||
};
|
||||
for (const ln of AIR_LANES) for (let i = 0; i < ln.n; i++) scan(ln.x, ln.y, (t) => laneZ(ln, i, t), 0);
|
||||
scan(FLYBY_X, FLYBY_Y, flybyZ, TIMES.flyby);
|
||||
return out.sort((a, b) => a.t - b.t);
|
||||
})();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The maglev: an elevated track over cross street 3, and its trains gliding past
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -22,6 +22,17 @@ export interface Ambience {
|
|||
fadeOut?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A one-shot sound that starts at meditation time `t`. It stays in step with the scene clock, so
|
||||
* after a pause or skip it resumes partway through. `pan` runs from -1 (left) to 1 (right).
|
||||
*/
|
||||
export interface Cue {
|
||||
t: number;
|
||||
src: string;
|
||||
volume?: number;
|
||||
pan?: number;
|
||||
}
|
||||
|
||||
export interface Meditation {
|
||||
id: string;
|
||||
title: string;
|
||||
|
|
@ -38,5 +49,7 @@ export interface Meditation {
|
|||
* list to layer several (e.g. rain and city noise) that play together.
|
||||
*/
|
||||
ambience?: Ambience | readonly Ambience[];
|
||||
/** Optional sound effects timed to moments in the scene, e.g. a car flying past. */
|
||||
cues?: readonly Cue[];
|
||||
createScene(): Scene;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { AmbientLoop, Music } from '../engine/audio';
|
||||
import { AmbientLoop, CueTrack, Music } from '../engine/audio';
|
||||
import { Loop } from '../engine/Loop';
|
||||
import { PixelCanvas } from '../engine/PixelCanvas';
|
||||
import type { Meditation, Scene } from '../meditations/types';
|
||||
|
|
@ -22,41 +22,48 @@ const ICONS = {
|
|||
'<svg viewBox="0 0 10 10" fill="currentColor"><path d="M1 1h3v1H2v2H1zM6 1h3v3H8V2H6zM1 6h1v2h2v1H1zM8 6h1v3H6V8h2z"/></svg>',
|
||||
};
|
||||
|
||||
/** Music plus any looping ambiences, driven together from the meditation clock. */
|
||||
/** Music plus any looping ambiences and timed cues, driven together from the meditation clock. */
|
||||
class Soundtrack {
|
||||
private readonly music: Music;
|
||||
private readonly ambience: AmbientLoop[];
|
||||
private readonly cues: CueTrack;
|
||||
|
||||
constructor(m: Meditation, enabled: boolean) {
|
||||
this.music = new Music(enabled ? m.music : undefined, 0.75);
|
||||
const list = enabled && m.ambience ? [m.ambience].flat() : [];
|
||||
this.ambience = list.map((a) => new AmbientLoop(a.src, a.volume, a.fadeIn, a.fadeOut, a.from, a.until));
|
||||
this.cues = new CueTrack(enabled ? m.cues : undefined);
|
||||
}
|
||||
|
||||
play(t: number): void {
|
||||
this.music.seek(t);
|
||||
this.music.play();
|
||||
for (const a of this.ambience) a.start(t);
|
||||
this.cues.start(t);
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.music.pause();
|
||||
for (const a of this.ambience) a.pause();
|
||||
this.cues.pause();
|
||||
}
|
||||
|
||||
seek(t: number): void {
|
||||
this.music.seek(t);
|
||||
for (const a of this.ambience) a.seek(t);
|
||||
this.cues.seek(t);
|
||||
}
|
||||
|
||||
update(t: number, duration: number): void {
|
||||
this.music.update(t, duration);
|
||||
for (const a of this.ambience) a.update(t, duration);
|
||||
this.cues.update(t, duration);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.music.destroy();
|
||||
for (const a of this.ambience) a.destroy();
|
||||
this.cues.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue