惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
U
Unit 42
H
Help Net Security
博客园_首页
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
aimingoo的专栏
aimingoo的专栏
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
S
Security @ Cisco Blogs
M
MIT News - Artificial intelligence
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
Spread Privacy
Spread Privacy
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
V
Vulnerabilities – Threatpost
WordPress大学
WordPress大学
C
Cisco Blogs
G
Google Developers Blog
N
News and Events Feed by Topic
P
Palo Alto Networks Blog
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
博客园 - 聂微东
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
O
OpenAI News
云风的 BLOG
云风的 BLOG
IT之家
IT之家
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
小众软件
小众软件
Scott Helme
Scott Helme
大猫的无限游戏
大猫的无限游戏
L
LINUX DO - 最新话题
Microsoft Azure Blog
Microsoft Azure Blog
Simon Willison's Weblog
Simon Willison's Weblog
N
News and Events Feed by Topic
F
Fortinet All Blogs
The Last Watchdog
The Last Watchdog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Sample-Free Drum Synthesis in Web Audio — Building Kick, Snare, and Hi-Hat from Oscillators in 60 Lines
SEN LLC · 2026-05-01 · via DEV Community

SEN LLC

Most drum machines on the web load .wav or .mp3 samples and play them back. That works, but you can also synthesise every voice from OscillatorNode, BufferSource-as-noise, and BiquadFilter — no audio files needed, no fetch wait, instant click-to-play.

Here's a 16-step drum machine where every voice is built in code (≈20 lines each), plus the acoustic reasoning behind why the recipes work.

drum-machine UI in the four-on-the-floor preset: Kick on steps 1/5/9/13, Snare on 5/13, Hi-hat on every other step, Open hat on 7/15. The playhead outline is on step 7. Dark theme.

🥁 Demo: https://sen.ltd/portfolio/drum-machine/
📦 GitHub: https://github.com/sen-ltd/drum-machine

Three knobs that make a sound feel like a drum

Three properties matter when synthesising a percussive hit:

Property What it controls How to set it
Energy curve How sharp the attack is, how fast it decays GainNode.gain with setValueAtTime + exponentialRampToValueAtTime
Spectrum The "colour" of the sound — dull, bright, metallic OscillatorNode.type (sine/triangle/square) + BiquadFilter
Pitch motion High at the attack, dropping into the body (the essence of a kick) frequency.exponentialRampToValueAtTime

Sample playback locks all three to "however the recording captured them." Synthesis lets you tune each one independently — small adjustments like "sharper attack" or "thicker body" become parameter changes.

Kick — sine sweep + fast amp decay

A real kick drum is "click" → "boom": the beater hits the head with a sharp transient, and the resonance of the shell decays into a low fundamental. One sine oscillator with a fast pitch sweep does this convincingly:

osc.frequency.setValueAtTime(150, time);                       // attack
osc.frequency.exponentialRampToValueAtTime(48, time + 0.05);   // body (50 ms)
amp envelope: 1.0  0.0001 over 450 ms (exponential)

Enter fullscreen mode Exit fullscreen mode

What matters:

  • The 150 Hz → 48 Hz drop creates the "click → boom." 150 alone is too pitched, 48 alone has no attack.
  • The 50 ms ramp is fast — humans hear sub-30-ms events as a single click, not as motion.
  • The 450 ms amp decay sits in the right pocket. Shorter sounds tinny ("pip"); longer drags the boom and crowds the next beat.
  • The waveform is always sine. Triangle or square add audible upper harmonics that read as "synth," not "drum."
export function playKick(ctx, time, dest, gain = 1) {
  const osc = ctx.createOscillator();
  osc.type = "sine";
  osc.frequency.setValueAtTime(150, time);
  osc.frequency.exponentialRampToValueAtTime(48, time + 0.05);

  const ampEnv = ctx.createGain();
  ampEnv.gain.setValueAtTime(0, time);
  ampEnv.gain.linearRampToValueAtTime(gain, time + 0.001);
  ampEnv.gain.exponentialRampToValueAtTime(0.0001, time + 0.45);

  osc.connect(ampEnv).connect(dest);
  osc.start(time);
  osc.stop(time + 0.5);
}

Enter fullscreen mode Exit fullscreen mode

Gotcha: exponentialRampToValueAtTime cannot reach 0 — it works in log space internally, where 0 is −∞. Aim for 0.0001 (or finish with an explicit setValueAtTime(0, end)). Forgetting this leaks audio between hits.

Snare — pitched body + bandpassed noise, mixed in parallel

A real snare is mostly noise. But noise alone reads as "ssshhh," not "snare." The trick is to layer a small pitched component that gives the hit a tonal centre:

[ triangle 200 Hz, 50 ms decay ] ─┐
                                   ├─→ master
[ noise → bandpass 1.5 kHz Q=0.6, 180 ms decay ] ─┘

Enter fullscreen mode Exit fullscreen mode

In code:

// Body: 200 Hz triangle, fast decay
const body = ctx.createOscillator();
body.type = "triangle";
body.frequency.setValueAtTime(200, time);
const bodyEnv = envelopedGain(ctx, time, 0.55, 0.05);  // 50 ms
body.connect(bodyEnv).connect(dest);
body.start(time);
body.stop(time + 0.07);

// Noise: white noise → bandpass → longer decay
const noise = ctx.createBufferSource();
noise.buffer = whiteNoiseBuffer;       // pre-allocated Float32Array
const filter = ctx.createBiquadFilter();
filter.type = "bandpass";
filter.frequency.value = 1500;
filter.Q.value = 0.6;
const noiseEnv = envelopedGain(ctx, time, 0.6, 0.18);  // 180 ms
noise.connect(filter).connect(noiseEnv).connect(dest);
noise.start(time);

Enter fullscreen mode Exit fullscreen mode

Key choices:

  • Bandpass at 1.5 kHz — the frequency range where snare "snap" lives. Move it lower and you get a tom; higher and it turns into a hi-hat.
  • Q = 0.6 is gentle filtering. Crank Q up to 5+ and it starts ringing like a struck cymbal — useful for percussion, wrong for a snare.
  • Triangle, not sine, for the body. Triangle adds odd-harmonic content; the snare reads firmer.
  • Cache the noise buffer. Allocate one Float32Array of white noise at start, reuse for every hit. Allocating per hit is several KB per beat, which the GC will eventually decide to handle inconveniently.

Hi-hat — square wave through a high-Q bandpass

The hi-hat sound is metal-on-metal: a dense cluster of high partials, decaying fast. Recipe:

osc.type = "square";          // square has rich odd harmonics → metallic
osc.frequency.setValueAtTime(7800, time);

filter.type = "bandpass";
filter.frequency.value = 7500;  // 7-8 kHz where cymbals live
filter.Q.value = 12;            // narrow band → "ringing" timbre

decay: closed = 40 ms / open = 320 ms

Enter fullscreen mode Exit fullscreen mode

What's load-bearing:

  • Square wave, not sine. Square's odd harmonics produce the metallic sheen; sine alone is a pure "blip."
  • Q = 12 is high — this filter rings, which is exactly what a cymbal does.
  • Closed and open hi-hats differ only in decay length — same oscillator, same filter, different envelope. No second voice needed.
export function playHat(ctx, time, dest, open = false, gain = 1) {
  const osc = ctx.createOscillator();
  osc.type = "square";
  osc.frequency.setValueAtTime(7800, time);

  const filter = ctx.createBiquadFilter();
  filter.type = "bandpass";
  filter.frequency.value = 7500;
  filter.Q.value = 12;

  const decay = open ? 0.32 : 0.04;
  const env = envelopedGain(ctx, time, 0.45 * gain, decay);

  osc.connect(filter).connect(env).connect(dest);
  osc.start(time);
  osc.stop(time + decay + 0.02);
}

Enter fullscreen mode Exit fullscreen mode

The lookahead scheduler — why setInterval doesn't work

Voicing is half the problem; the other half is firing the voices on time. The naive shape:

setInterval(() => playStep(currentStep++), 60000 / bpm / 4);

Enter fullscreen mode Exit fullscreen mode

…drifts. The JS event loop has no commitment to firing on schedule. GC, layout, another extension's content script — any of them can delay the callback by 5-50 ms, and the error accumulates.

The fix from Chris Wilson's "A Tale of Two Clocks" is to schedule against the audio clock, not the JS clock:

function tick() {
  while (state.nextStepTime < audioCtx.currentTime + 0.1) {
    onStep({ step: state.step, time: state.nextStepTime });
    state.nextStepTime += secondsPerStep();
    state.step = (state.step + 1) % stepsPerBar;
  }
}
setInterval(tick, 25);   // 25 ms poll, 100 ms lookahead = 75 ms of slack

Enter fullscreen mode Exit fullscreen mode

The mental model:

  1. audioCtx.currentTime is the actual audio renderer's clock — sample-accurate.
  2. osc.start(t) can take a future time; the audio thread renders the sample at t exactly, regardless of what JS is doing.
  3. The JS timer's only job is to keep the queue topped up with the next 100 ms of events.
  4. Even if JS stalls for 50 ms, the audio thread has already received the next several hits and renders them on time.

The result is drift-free timing, audible immediately if you A/B against the naive version on anything other than a quiet, idle browser tab.

Tests — fake the AudioContext

Synthesis correctness ("does the kick sound like a kick?") is verified by ear in real Chrome. The scheduler, however, is fully testable without an audio engine — inject a fake audioCtx (just a currentTime field) and a fake setInterval:

function makeFakes() {
  const audio = { currentTime: 0 };
  const intervals = [];
  const setIntervalFn = (fn) => {
    intervals.push({ fn, cleared: false });
    return intervals.length - 1;
  };
  const advance = (sec) => {
    audio.currentTime += sec;
    for (const slot of intervals) if (!slot.cleared) slot.fn();
  };
  return { audio, setIntervalFn, advance, /* ... */ };
}

test("at 120 BPM, 16 steps per bar = 0.125 s per step", () => {
  const fakes = makeFakes();
  const queued = [];
  const sched = createScheduler({
    audioCtx: fakes.audio,
    bpm: 120, stepsPerBar: 16, beatsPerBar: 4,
    onStep: ({ time }) => queued.push(time),
    setIntervalFn: fakes.setIntervalFn,
    clearIntervalFn: fakes.clearIntervalFn,
  });
  sched.start();
  fakes.advance(1.0);
  for (let i = 1; i < queued.length; i++) {
    assert.ok(Math.abs(queued[i] - queued[i - 1] - 0.125) < 1e-9);
  }
});

Enter fullscreen mode Exit fullscreen mode

17 tests run under node --test in 70 ms. No browser, no jsdom.

Takeaways

  • Kick: sine 150 Hz → 48 Hz exponential sweep, 450 ms amp decay. The pitch sweep is the magic; the decay length is the pocket.
  • Snare: triangle 200 Hz body (50 ms) layered with bandpassed white noise at 1.5 kHz Q=0.6 (180 ms). Noise alone reads as "shhh"; the body gives the hit a tonal centre.
  • Hi-hat: square 7.8 kHz through bandpass 7.5 kHz Q=12. Closed (40 ms) and open (320 ms) differ only in envelope decay — same nodes, two voices.
  • exponentialRampToValueAtTime(0, …) doesn't work — log space has no zero. Use 0.0001 or finish with setValueAtTime(0, end).
  • Lookahead scheduler (Chris Wilson pattern): 25 ms JS poll, 100 ms ahead queue, drift-free under main-thread jitter.
  • Inject the audio clock for tests so the scheduler is verified deterministically without booting an AudioContext.

Full source on GitHub. MIT.

Third in the Web Audio series: metronome (timing) → pitch-detector (analysis) → drum-machine (synthesis).