示例
实用示例,实时演示。
挑一个示例全屏打开,运行效果和源码并排呈现。
挑一个示例全屏打开,运行效果和源码并排呈现。
一个带着自己时钟的库。Web Audio 在自己的时间线上提前调度每个音符,节奏模式是一个普通的二维布尔数组,网格负责切换其中的值,调度器负责读取它,所以你点一下,下一轮就能听到。播放头只有在当前播放的步进位置变化时,才会更新自己的 scope()。音频在第一次点 Play 时启动,卸载时通过清理函数关闭,所以只要离开这个示例,声音就停了。
Space plays and stops. Flip cells while it plays: the engine reads the same array, so you hear the change on the next pass.
// app.ts: the sequencer. The audio engine owns the clock; the UI never times a // note. The pattern is a plain 2D array of booleans: a cell flips its entry, // and the engine reads the same array as it books each step, so a click while // playing is heard on the next pass. While playing, a rAF loop asks the engine // which step is audible and updates the grid only when the answer changes. // No audio exists until the first Play, and the mount cleanup closes it: // leaving the example stops the sound. The song itself is kept. import "nuclo"; import { createEngine, STEPS, TRACKS, type Engine, type Song } from "./audio.ts"; import { s } from "./styles.ts"; const hits = (line: string) => [...line].map((c) => c === "x"); // One line per track, in TRACKS order: x is a hit. const PRESETS: Record<string, string[]> = { "Four on the floor": ["x...x...x...x...", "................", "....x.......x...", "x...x...x...x...", "..x...x...x...x.", "..x...x...x...x.", "x..x..x...x..x.."], Breakbeat: ["x.x.......xx....", "....x..x.x..x..x", "................", "x.x.x.x.x...x.x.", "..........x.....", "x.x.......x.....", "......x.......x."], "Hip hop": ["x.......x.x.....", "....x.......x...", "....x.......x...", "x.x.x.x.x.x.x.x.", "................", "x.......x.x.....", "..x.....x.....x."], }; const DENSITY = [0.3, 0.15, 0.1, 0.5, 0.1, 0.3, 0.2]; // Randomize: the chance of a hit on each step, per track const song: Song = { bpm: 112, swing: 0, pattern: PRESETS["Four on the floor"].map(hits), mix: TRACKS.map(() => ({ volume: 0.8, muted: false })), }; // Built on the first Play, never here: the server imports this module too, and // browsers only let an AudioContext start after a click. let engine: Engine | null = null; let playhead = -1; // the audible step, as last read from the engine let frame = 0; const playing = () => engine?.playing ?? false; function play() { engine ??= createEngine(song); engine.play(); frame = requestAnimationFrame(follow); update(); } function stop() { engine?.stop(); cancelAnimationFrame(frame); playhead = -1; update(); } const toggle = () => (playing() ? stop() : play()); // Every frame while playing. The step changes 4 to 12 times a second, so most frames touch nothing. function follow() { const now = engine!.step; if (now !== playhead) { playhead = now; update("seq-grid"); } frame = requestAnimationFrame(follow); } function load(pattern: boolean[][]) { song.pattern = pattern; update(); } function Cell(track: number, step: number) { return button(s.cell, { "aria-label": `${TRACKS[track]}, step ${step + 1}`, "aria-pressed": () => String(song.pattern[track][step]), class: () => cx(s.cell, step === playhead ? s.now : null).className, onClick: () => { song.pattern[track][step] = !song.pattern[track][step]; update(); }, }); } function Track(name: string, track: number) { const mix = song.mix[track]; return div( s.track, { class: () => cx(s.track, mix.muted ? s.muted : null).className }, div( s.head, span(s.name, name), button(s.mute, { title: `Mute ${name}`, "aria-pressed": () => String(mix.muted), onClick: () => { mix.muted = !mix.muted; update(); } }, "M"), input(s.volume, { type: "range", min: "0", max: "1", step: "0.05", value: String(mix.volume), "aria-label": `${name} volume` }, { onInput: (e) => { mix.volume = Number(e.currentTarget.value); } }), ), // Four beats of four steps: the gap between groups is the beat. ...[0, 4, 8, 12].map((beat) => div(s.beat, ...[0, 1, 2, 3].map((i) => Cell(track, beat + i)))), ); } export function StepSequencer() { return div( s.app, on("mount", () => { // Capture: Space is handled before the modal's own document listener sees it. // A focused control is left alone, since a button already answers Space with a click. const onKey = (e: KeyboardEvent) => { if (e.key !== " " || (e.target as Element).closest("button, input, select, textarea")) return; e.preventDefault(); toggle(); }; document.addEventListener("keydown", onKey, { capture: true }); return () => { document.removeEventListener("keydown", onKey, { capture: true }); cancelAnimationFrame(frame); engine?.dispose(); // closes the AudioContext: nothing keeps playing engine = null; playhead = -1; }; }), div( s.bar, button(s.btn, s.primary, { title: "Shortcut: Space" }, () => (playing() ? "■ Stop" : "▶ Play"), { onClick: toggle }), label(s.field, "BPM", input({ type: "range", min: "60", max: "180", value: String(song.bpm) }, { onInput: (e) => { song.bpm = Number(e.currentTarget.value); update(); } }), span(s.readout, () => String(song.bpm))), label(s.field, "Swing", input({ type: "range", min: "0", max: "0.5", step: "0.05", value: String(song.swing) }, { onInput: (e) => { song.swing = Number(e.currentTarget.value); update(); } }), span(s.readout, () => `${Math.round(song.swing * 100)}%`)), ), div( s.bar, ...Object.entries(PRESETS).map(([name, lines]) => button(s.btn, name, { onClick: () => load(lines.map(hits)) })), button(s.btn, "Randomize", { onClick: () => load(DENSITY.map((d) => Array.from({ length: STEPS }, () => Math.random() < d))) }), button(s.btn, "Clear", { onClick: () => load(TRACKS.map(() => Array(STEPS).fill(false))) }), ), // scope("seq-grid"): the rAF loop calls update("seq-grid"), which runs the // bindings in here and skips the toolbars above. div(s.grid, scope("seq-grid"), ...TRACKS.map(Track)), p(s.hint, "Space plays and stops. Flip cells while it plays: the engine reads the same array, so you hear the change on the next pass."), ); }
// audio.ts: a drum machine with no UI. Web Audio owns the clock: every note is // booked ahead on the AudioContext timeline, so a busy main thread can delay // the booking but never the beat (the "Tale of Two Clocks" scheduler). The // engine reads the song, a plain object the UI edits too, each time it books a // step, and it answers which step is heard right now. Every sound is // synthesized: oscillators, one buffer of noise, filters and envelopes. export const TRACKS = ["Kick", "Snare", "Clap", "Hat", "Open hat", "Bass", "Pluck"]; export const STEPS = 16; export interface Song { bpm: number; swing: number; // 0 is straight; at 1/3 every second 16th lands on a triplet pattern: boolean[][]; // pattern[track][step] mix: { volume: number; muted: boolean }[]; // one per track } export interface Engine { readonly playing: boolean; readonly step: number; // the step heard right now, -1 when stopped play(): void; stop(): void; dispose(): void; } const LOOKAHEAD = 0.1; // s: how far ahead notes are booked const TICK = 25; // ms between bookings: the overlap with LOOKAHEAD absorbs a late timer const hz = (midi: number) => 440 * 2 ** ((midi - 69) / 12); // The tonal tracks play a fixed line, one note per step: the grid decides which notes sound. const BASS = [45, 45, 57, 45, 48, 48, 60, 48, 43, 43, 55, 43, 50, 50, 52, 55].map(hz); const PLUCK = [69, 72, 76, 79, 81, 79, 76, 72, 74, 76, 79, 81, 79, 76, 74, 72].map(hz); export function createEngine(song: Song): Engine { const ctx = new AudioContext(); const master = new GainNode(ctx, { gain: 0.8 }); master.connect(new DynamicsCompressorNode(ctx)).connect(ctx.destination); // keeps a busy step from clipping const noise = new AudioBuffer({ length: ctx.sampleRate, sampleRate: ctx.sampleRate }); // one second, shared by every noisy voice const samples = noise.getChannelData(0); for (let i = 0; i < samples.length; i++) samples[i] = Math.random() * 2 - 1; // A gain into the master: `peak` at time t, then a fall to silence over `decay` seconds. function envelope(t: number, peak: number, decay: number) { const gain = new GainNode(ctx); gain.gain.setValueAtTime(peak, t); gain.gain.exponentialRampToValueAtTime(0.001, t + decay); gain.connect(master); return gain; } function tone(type: OscillatorType, freq: number, t: number, decay: number, peak: number) { const osc = new OscillatorNode(ctx, { type }); osc.frequency.setValueAtTime(freq, t); osc.connect(envelope(t, peak, decay)); osc.start(t); osc.stop(t + decay); return osc; } function hiss(type: BiquadFilterType, freq: number, t: number, decay: number, peak: number) { const src = new AudioBufferSourceNode(ctx, { buffer: noise }); src.connect(new BiquadFilterNode(ctx, { type, frequency: freq })).connect(envelope(t, peak, decay)); src.start(t); src.stop(t + decay); } // One voice per track, in TRACKS order: t is the time, v the track volume, i the step. const voices: ((t: number, v: number, i: number) => void)[] = [ (t, v) => tone("sine", 150, t, 0.4, v).frequency.exponentialRampToValueAtTime(45, t + 0.1), // a falling sine (t, v) => { hiss("highpass", 1500, t, 0.16, v * 0.6); tone("triangle", 185, t, 0.08, v * 0.5); }, (t, v) => [0, 0.012, 0.024].forEach((d, n) => hiss("bandpass", 1200, t + d, n < 2 ? 0.012 : 0.18, v * 0.9)), // three bursts, the last rings (t, v) => hiss("highpass", 7000, t, 0.05, v * 0.4), (t, v) => hiss("highpass", 7000, t, 0.3, v * 0.3), (t, v, i) => tone("sawtooth", BASS[i], t, 0.2, v * 0.3), (t, v, i) => tone("triangle", PLUCK[i], t, 0.25, v * 0.35), ]; const queue: { step: number; time: number }[] = []; // booked steps, oldest first let timer: ReturnType<typeof setInterval> | undefined; let next = 0; // the next step to book let nextTime = 0; // when it sounds, on the AudioContext clock // Books every step that starts within the lookahead. A cell toggled now is heard the next time its step is booked. function book() { while (nextTime < ctx.currentTime + LOOKAHEAD) { song.pattern.forEach((row, track) => { const { volume, muted } = song.mix[track]; if (row[next] && !muted) voices[track](nextTime, volume, next); }); queue.push({ step: next, time: nextTime }); // Swing lengthens even 16ths and shortens odd ones by the same amount, so every beat keeps its length. nextTime += (15 / song.bpm) * (next % 2 ? 1 - song.swing : 1 + song.swing); next = (next + 1) % STEPS; } } function stop() { clearInterval(timer); timer = undefined; queue.length = 0; } return { get playing() { return timer !== undefined; }, // Steps are booked up to LOOKAHEAD early: the one heard is the last whose time has come. get step() { while (queue.length > 1 && queue[1].time <= ctx.currentTime) queue.shift(); return queue.length && queue[0].time <= ctx.currentTime ? queue[0].step : -1; }, play() { if (timer !== undefined) return; ctx.resume(); next = 0; nextTime = ctx.currentTime + 0.05; book(); timer = setInterval(book, TICK); }, stop, dispose() { stop(); ctx.close(); }, }; }
import "nuclo"; const mono = "ui-monospace, monospace"; const control = { height: "34px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem", fontWeight: "600" }; export const s = { app: css("seq-app", { display: "flex", flexDirection: "column", gap: "10px", width: "100%", height: "100%" }), bar: css("seq-bar", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px" }), btn: css("seq-btn", { ...control, whiteSpace: "nowrap", hover: { backgroundColor: "var(--c-bg-secondary)" } }), primary: css("seq-primary", { minWidth: "92px", backgroundColor: "var(--c-primary-dark)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--c-primary-dark)", filter: "brightness(0.92)" } }), field: css("seq-field", { display: "flex", alignItems: "center", gap: "8px", fontSize: "0.8125rem", color: "var(--c-text-dim)", "& input": { width: "110px", accentColor: "var(--c-primary)" } }), readout: css("seq-readout", { minWidth: "4ch", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text)", fontVariantNumeric: "tabular-nums" }), // The grid scrolls sideways on phones; every row is at least as wide as its content, so the sticky heads stay put. grid: css("seq-grid", { display: "flex", flexDirection: "column", gap: "6px", flex: "0 1 auto", minHeight: "0", overflow: "auto", padding: "10px 10px 10px 0", borderRadius: "12px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-secondary)" }), track: css("seq-track", { display: "flex", gap: "10px", minWidth: "max-content" }), muted: css("seq-muted", { "& > div + div": { opacity: "0.35" } }), head: css("seq-head", { position: "sticky", left: "0", zIndex: 1, display: "flex", alignItems: "center", gap: "6px", width: "170px", flexShrink: 0, padding: "0 4px 0 10px", backgroundColor: "var(--c-bg-secondary)", "@media (max-width: 599px)": { width: "136px", gap: "4px", padding: "0 2px 0 8px" } }), name: css("seq-name", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.8125rem", fontWeight: "600" }), mute: css("seq-mute", { width: "26px", height: "26px", flexShrink: 0, borderRadius: "6px", border: "1px solid var(--c-border-light)", fontSize: "0.6875rem", fontWeight: "700", color: "var(--c-text-dim)", hover: { color: "var(--c-text)" }, "&[aria-pressed=true]": { backgroundColor: "var(--c-text-dim)", borderColor: "transparent", color: "var(--c-bg)" } }), volume: css("seq-volume", { width: "52px", flexShrink: 0, accentColor: "var(--c-primary)", "@media (max-width: 599px)": { width: "36px" } }), beat: css("seq-beat", { display: "flex", gap: "3px", flex: "1" }), cell: css("seq-cell", { flex: "1", minWidth: "26px", height: "34px", borderRadius: "6px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", cursor: "pointer", "@media (min-width: 900px)": { height: "44px" }, hover: { borderColor: "var(--c-primary)" }, "&[aria-pressed=true]": { backgroundColor: "var(--c-primary)", borderColor: "var(--c-primary)" } }), // The playhead column: lit when empty, brighter when it plays a hit. now: css("seq-now", { backgroundColor: "var(--c-primary-alpha-19)", "&[aria-pressed=true]": { backgroundColor: "var(--c-accent-secondary)", borderColor: "var(--c-accent-secondary)" } }), hint: css("seq-hint", { fontSize: "0.8125rem", color: "var(--c-text-dim)" }), };