import { Mixer, SR, chime, envelope, pop, shimmer, slowDown, tick, whoosh } from './audio' import { CardRenderer, FPS, MAX_COMPACT, makeTimeline, type CardSpec, type Timeline } from './renderer' export interface SfxSettings { whoosh: boolean tick: boolean chime: boolean shimmer: boolean pop: boolean volume: number // 0..1.5 } export interface VoiceSettings { clip: Float32Array | null second: 'slow' | 'same' | 'none' volume: number } export interface Built { T: Timeline renderer: CardRenderer mixer: Mixer fitted: 'slow' | 'same' | 'none' // what the second reading became after fitting into 3 s voiceCut: boolean // the first reading itself runs past the end } let sfxCache: Record | null = null function sfx() { if (!sfxCache) sfxCache = { whoosh: whoosh(), chime: chime(), shimmer: shimmer(), pop: pop() } return sfxCache } const ticks: Float32Array[] = [] const tickAt = (i: number) => (ticks[i] ??= tick(i)) export function build(spec: CardSpec, voice: VoiceSettings, fx: SfxSettings): Built { const v1 = voice.clip const d1 = v1 ? v1.length / SR : 0.7 let v2: Float32Array | null = null let fitted: Built['fitted'] = voice.second if (v1 && voice.second !== 'none') { const options: ['slow' | 'same', Float32Array][] = voice.second === 'slow' ? [['slow', slowDown(v1, 0.8)], ['same', v1]] : [['same', v1]] if (spec.compact) { const base = makeTimeline(spec, d1, null) const ok = options.find(([, c]) => base.en1 + d1 + 0.1 + c.length / SR + 0.1 <= MAX_COMPACT) v2 = ok ? ok[1] : null fitted = ok ? ok[0] : 'none' } else v2 = options[0][1] } const d2 = v2 ? v2.length / SR : null const T = makeTimeline(spec, d1, d2) const mx = new Mixer(T.dur) const g = fx.volume const S = sfx() if (fx.whoosh) mx.add(S.whoosh, T.rev - 0.06, 0.9 * g) if (fx.tick) { const n = spec.en.length let k = 0 ;[...spec.en].forEach((c, i) => { if (c === ' ') return mx.add(tickAt(k), T.type0 + k * T.dt, 0.9 * g, (i / Math.max(n - 1, 1)) * 1.2 - 0.6) k++ }) } if (fx.chime) mx.add(S.chime, T.done, 0.85 * g) if (fx.shimmer) mx.add(S.shimmer, T.done + 0.1, g) if (fx.pop) { mx.add(S.pop, T.ipa, 0.7 * g) mx.add(S.pop, T.mean, 0.5 * g) } const env = new Float32Array(T.nf + 2) if (v1) mx.add(v1, T.en1, voice.volume) if (v2 && T.en2 != null) mx.add(v2, T.en2, voice.volume) for (const [clip, st] of [[v1, T.en1], [v2, T.en2]] as [Float32Array | null, number | null][]) { if (!clip || st == null) continue const e = envelope(clip, FPS) const s = Math.round(st * FPS) for (let i = 0; i < e.length && s + i < env.length; i++) env[s + i] = Math.max(env[s + i], e[i]) } const sm = env.map((_, i) => 0.25 * (env[i - 1] ?? 0) + 0.5 * env[i] + 0.25 * (env[i + 1] ?? 0)) mx.finish() return { T, renderer: new CardRenderer(spec, T, sm), mixer: mx, fitted, voiceCut: !!v1 && T.en1 + d1 > T.dur + 0.02 } }