Building a Browser-Based Drum Machine: Web Audio API Deep Dive

Building a Browser-Based Drum Machine: Web Audio API Deep Dive

构建一个基于浏览器的鼓机:Web Audio API 深入解析

https://zovo.one/free-tools/drum-machine/

Web Audio API 是浏览器 API 中最强大、但最难理解的之一。它可以合成声音、实时处理音频,并保持样本精确的时序。构建鼓机可以训练这些能力,并让你学会在浏览器中的任何音频应用都适用的模式。

为什么要有 Web Audio API
在 Web Audio API 之前,浏览器的音频仅限于

// Source -> Gain -> Destination
const source = ctx.createBufferSource();
const gain = ctx.createGain();

source.connect(gain);
gain.connect(ctx.destination);

时序就是一切
鼓机的根本挑战是准确的时序。用 setInterval 或 setTimeout 来调度音乐事件并不可行,因为 JavaScript 的事件循环大约只有 4-16 毫秒的精度。在 120 BPM 下,一个六teenth 音符是 125ms。大约 16ms 的抖动就会被听成“拖沓”的节拍。
Web Audio API 通过自己的高精度时钟(ctx.currentTime)解决了这一点,它在音频线程上运行,独立于主 JavaScript 线程。
pattern 是一个“向前看调度器”:

LOOKAHEAD = 25 毫秒 // 提前查看
SCHEDULE_AHEAD = 0.1 // 以秒为单位,提前调度

let nextNoteTime = 0;
let currentStep = 0;

function scheduler() {
while (nextNoteTime < ctx.currentTime + SCHEDULE_AHEAD) { scheduleNote(currentStep, nextNoteTime); advanceStep(); } setTimeout(scheduler, LOOKAHEAD); } 调度器每 25ms 运行一次(使用 setTimeout 的不精确时序),并使用精确的 ctx.currentTime 来调度音符。只要前瞻窗口大于 setTimeout 的抖动,每个音符都能以样本精确的时序被调度。 加载与播放采样 鼓机通常使用录制的采样(踢鼓、军鼓、踩镲等)。将它们加载为 AudioBuffer: async function loadSample(url) { const response = await fetch(url); const arrayBuffer = await response.arrayBuffer(); return ctx.decodeAudioData(arrayBuffer); } function playSample(buffer, time) { const source = ctx.createBufferSource(); source.buffer = buffer; source.connect(ctx.destination); source.start(time); } 每个 createBufferSource() 都是一次性使用的。你不能重复播放同一个源节点;每次需要新建一个。这看起来有点浪费,但这是设计之初——浏览器会在内部进行优化。 步进序器模式 鼓机通常有 16 个步进(在 4/4 拍子中一个小节的六teenth 音符)。每个乐器有一行 16 个按钮。如果按钮处于活动状态,样本会在该步奏上播放。 const pattern = { kick: [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0], snare: [0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0], hihat: [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0], }; function scheduleNote(step, time) { for (const [instrument, steps] of Object.entries(pattern)) { if (steps[step]) { playSample(samples[instrument], time); } } } 添加“人性化” 完全量化的节拍会听起来很生硬。真正的鼓手在时序和力度上有微小的变动。通过引入微小的随机变化来加入人性化: function humanize(time, amount = 0.01) { return time + (Math.random() - 0.5) * amount; } function playWithVelocity(buffer, time, velocity) { const source = ctx.createBufferSource(); const gain = ctx.createGain(); gain.gain.value = velocity; source.buffer = buffer; source.connect(gain); gain.connect(ctx.destination); source.start(time); } 力度波动 +/-20%、时序波动 +/-10ms 就能明显提升手感,而又不会听起来很混乱。 工具 如果你需要一个可直接使用的浏览器鼓机,具备预设模式、可调 tempo、以及多款鼓组声音,我在 zovo.one/free-tools/drum-machine 上实现了一个。它实现了上述所有模式,并提供可视化的步进序列界面。 我是 Michael Lip。我在 zovo.one 构建免费开发者工具。500 多个工具,全部私有、全部免费。 HI-FI News 来自 DEV Community: javascript https://dev.to/t/javascript 发布日期:2026 年 3 月 25 日 03:40AM March 25, 2026 at 03:40AM