flyyt / src /flyBuzz.ts
gpue's picture
Deploy 771c7d3cfb0b08d632f7fe3d02e59b7bcdff47c4
5a3b695 verified
Raw History Blame Contribute Delete
9.49 kB
/**
* Audible buzzing per fly, pitched by wingbeat drive -- the audio counterpart
* to wingController.ts's visual flap. Each fly gets its own two-oscillator
* (left/right wing) node graph feeding a single shared master volume.
*
* The AudioContext is built lazily and only resumed on a user gesture (browser
* autoplay policy), never at import time -- see resumeAudioContext().
*/
import { DRIVE_THRESHOLD } from "./wingController";
const MEDIUM_VOLUME = 0.5; // fixed master level -- no volume control
const AUDIO_MIN_HZ = 150; // audible insect-buzz register -- not the real ~200Hz wingbeat itself
const AUDIO_MAX_HZ = 250;
const MAX_GAIN_PER_SIDE = 0.15; // keeps many simultaneous flies from summing into clipping
const FILTER_HZ = 1500; // tames the sawtooth's harmonics into a drone rather than a buzz-saw
const PARAM_SMOOTH_TAU_S = 0.03; // bridges per-frame discreteness into a continuous ramp
const DISPOSE_FADE_S = 0.02; // avoids an audible click when a fly's sound is torn down
const DETUNE_SPREAD_CENTS = 8; // per-fly random detune so many flies don't phase-lock into one tone
// A human-bite "chomp" is granular, not one smooth tone: several tiny,
// irregularly-pitched noise "grains" scattered across a short window (teeth
// fracturing through food unevenly -- a crackle, not a swept filter) plus a
// sharp, pitch-dropping low thump underneath (the jaw's own percussive
// impact). One smooth filtered noise sweep reads as a synthesized "swoosh";
// scattered grains read as an actual crunch.
const BITE_GRAIN_COUNT = 7;
const BITE_GRAIN_DURATION_S = 0.02; // each grain very short -- the crackle texture
const BITE_GRAIN_SPREAD_S = 0.07; // grains land at random times within this window
const BITE_GRAIN_GAIN = 0.45;
const BITE_GRAIN_MIN_HZ = 1200; // bandpass center per grain, randomized per-grain
const BITE_GRAIN_MAX_HZ = 4200;
const BITE_GRAIN_Q = 0.8;
const BITE_THUMP_DURATION_S = 0.07; // short and punchy, not a sustained tone
const BITE_THUMP_START_HZ = 170;
const BITE_THUMP_END_HZ = 55;
const BITE_THUMP_GAIN = 0.55;
let ctx: AudioContext | null = null;
let master: GainNode | null = null;
let compressor: DynamicsCompressorNode | null = null;
function ensureAudio(): void {
if (ctx) return;
ctx = new AudioContext();
master = ctx.createGain();
master.gain.value = MEDIUM_VOLUME;
compressor = ctx.createDynamicsCompressor();
master.connect(compressor);
compressor.connect(ctx.destination);
}
/** Must be called from a user gesture handler (browser autoplay policy). Safe to call repeatedly. */
export function resumeAudioContext(): void {
ensureAudio();
if (ctx!.state === "suspended") void ctx!.resume();
}
interface WingVoice {
osc: OscillatorNode;
gain: GainNode;
}
export interface FlySound {
left: WingVoice;
right: WingVoice;
filter: BiquadFilterNode;
panner: StereoPannerNode;
flyGain: GainNode;
}
function createVoice(audioCtx: AudioContext, detuneCents: number): WingVoice {
const osc = audioCtx.createOscillator();
osc.type = "sawtooth";
osc.frequency.value = AUDIO_MIN_HZ;
osc.detune.value = detuneCents;
const gain = audioCtx.createGain();
gain.gain.value = 0;
osc.connect(gain);
osc.start();
return { osc, gain };
}
/** Requires resumeAudioContext() to have already run; returns null otherwise. */
export function createFlySound(): FlySound | null {
if (!ctx || !master) return null;
const left = createVoice(ctx, (Math.random() * 2 - 1) * DETUNE_SPREAD_CENTS);
const right = createVoice(ctx, (Math.random() * 2 - 1) * DETUNE_SPREAD_CENTS);
const filter = ctx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = FILTER_HZ;
const panner = ctx.createStereoPanner();
const flyGain = ctx.createGain();
left.gain.connect(filter);
right.gain.connect(filter);
filter.connect(panner);
panner.connect(flyGain);
flyGain.connect(master);
return { left, right, filter, panner, flyGain };
}
// wingController.ts's angle = min(sin(phase) * smoothedDrive * MAX_AMPLITUDE_RAD, 0) -- the
// wing is only actually moving (raising) during the negative half of sin(phase), and sits still
// at the folded rest pose the rest of the cycle. max(0, -sin(phase)) reconstructs that same
// 0-1 "is it moving right now" envelope from phase alone, so the buzz pulses in lockstep with
// the visible flap instead of playing a constant tone for as long as drive is nonzero.
function motionEnvelope(phase: number): number {
return Math.max(0, -Math.sin(phase));
}
function updateVoice(voice: WingVoice, drive: number, phase: number): void {
const now = ctx!.currentTime;
const audible = drive > DRIVE_THRESHOLD;
const targetGain = audible ? drive * motionEnvelope(phase) * MAX_GAIN_PER_SIDE : 0;
voice.gain.gain.setTargetAtTime(targetGain, now, PARAM_SMOOTH_TAU_S);
// Only move pitch while audible -- freezing it during silence (gain is already
// 0) avoids an audible pitch-swoop the next time the fly starts buzzing.
if (audible) {
const targetFreq = AUDIO_MIN_HZ + drive * (AUDIO_MAX_HZ - AUDIO_MIN_HZ);
voice.osc.frequency.setTargetAtTime(targetFreq, now, PARAM_SMOOTH_TAU_S);
}
}
export function updateFlySound(sound: FlySound, leftDrive: number, rightDrive: number, leftPhase: number, rightPhase: number): void {
updateVoice(sound.left, leftDrive, leftPhase);
updateVoice(sound.right, rightDrive, rightPhase);
}
/** distanceGain: 0 (silent, far from camera) - 1 (full volume, close to camera). pan: -1 (left) - 1 (right). */
export function updateFlySpatial(sound: FlySound, distanceGain: number, pan: number): void {
const now = ctx!.currentTime;
sound.flyGain.gain.setTargetAtTime(Math.min(1, Math.max(0, distanceGain)), now, PARAM_SMOOTH_TAU_S);
sound.panner.pan.setTargetAtTime(Math.min(1, Math.max(-1, pan)), now, PARAM_SMOOTH_TAU_S);
}
/** A single burst of white noise, freshly generated per bite (infrequent,
* user-triggered -- no need to cache/reuse a buffer). */
function createNoiseBuffer(audioCtx: AudioContext, durationS: number): AudioBuffer {
const length = Math.max(1, Math.floor(audioCtx.sampleRate * durationS));
const buffer = audioCtx.createBuffer(1, length, audioCtx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) data[i] = Math.random() * 2 - 1;
return buffer;
}
/**
* One-shot "bite" sound effect (Enter key, feeding on a resting fruit) --
* a human-bite "chomp," not a synth tone: several short, randomly-pitched
* noise grains scattered across a small window (an irregular crackle, the
* sound of teeth fracturing through food) layered with a sharp low thump
* (the jaw's own percussive impact). Reuses the same lazily-created
* ctx/master singletons as the continuous per-fly buzz (not a second
* AudioContext); same gain-envelope + scheduled-stop +
* disconnect-on-"ended" shape as disposeFlySound. No-op if
* resumeAudioContext() hasn't run yet.
*/
export function playBiteSound(): void {
if (!ctx || !master) return;
const audioCtx = ctx;
const audioMaster = master;
const now = audioCtx.currentTime;
for (let i = 0; i < BITE_GRAIN_COUNT; i++) {
const startAt = now + Math.random() * BITE_GRAIN_SPREAD_S;
const grain = audioCtx.createBufferSource();
grain.buffer = createNoiseBuffer(audioCtx, BITE_GRAIN_DURATION_S);
const grainFilter = audioCtx.createBiquadFilter();
grainFilter.type = "bandpass";
grainFilter.frequency.value = BITE_GRAIN_MIN_HZ + Math.random() * (BITE_GRAIN_MAX_HZ - BITE_GRAIN_MIN_HZ);
grainFilter.Q.value = BITE_GRAIN_Q;
const grainGain = audioCtx.createGain();
const gain = BITE_GRAIN_GAIN * (0.6 + Math.random() * 0.4); // slight per-grain loudness variation
grainGain.gain.setValueAtTime(gain, startAt);
grainGain.gain.exponentialRampToValueAtTime(0.001, startAt + BITE_GRAIN_DURATION_S);
grain.connect(grainFilter);
grainFilter.connect(grainGain);
grainGain.connect(audioMaster);
grain.start(startAt);
grain.stop(startAt + BITE_GRAIN_DURATION_S);
grain.addEventListener("ended", () => {
grain.disconnect();
grainFilter.disconnect();
grainGain.disconnect();
});
}
const thump = audioCtx.createOscillator();
thump.type = "sine";
thump.frequency.setValueAtTime(BITE_THUMP_START_HZ, now);
thump.frequency.exponentialRampToValueAtTime(BITE_THUMP_END_HZ, now + BITE_THUMP_DURATION_S);
const thumpGain = audioCtx.createGain();
thumpGain.gain.setValueAtTime(BITE_THUMP_GAIN, now);
thumpGain.gain.exponentialRampToValueAtTime(0.001, now + BITE_THUMP_DURATION_S);
thump.connect(thumpGain);
thumpGain.connect(audioMaster);
thump.start(now);
thump.stop(now + BITE_THUMP_DURATION_S);
thump.addEventListener("ended", () => {
thump.disconnect();
thumpGain.disconnect();
});
}
export function disposeFlySound(sound: FlySound): void {
const now = ctx!.currentTime;
const fadeDurationS = DISPOSE_FADE_S * 4;
sound.flyGain.gain.setTargetAtTime(0, now, DISPOSE_FADE_S);
const stopAt = now + fadeDurationS;
for (const voice of [sound.left, sound.right]) {
voice.osc.stop(stopAt);
voice.osc.addEventListener("ended", () => {
voice.osc.disconnect();
voice.gain.disconnect();
});
}
// Deferred so the flyGain fade above is actually audible instead of being
// cut off by an immediate disconnect.
setTimeout(() => {
sound.filter.disconnect();
sound.panner.disconnect();
sound.flyGain.disconnect();
}, fadeDurationS * 1000);
}