Skip to content

Drum Machine: Vanilla TS Event Pattern ​

Listen to the kick as the highlight moves across the grid. Each beat event carries a step index, including on rests. The demo uses that index to highlight the same column across the kick, snare and hi-hat lanes.

The same machine in plain JavaScript.

120 BPM
Event-Based
KICK
SNARE
HIHAT

Build a step row ​

Give the drum machine an empty container. The TypeScript below creates its Play button and 16 editable steps. Save a copy of the kick recording in your app’s public assets.

html
<div id="kick"></div>
<style>
  #kick [aria-pressed="true"] { background: #22316f; color: white; }
  #kick .current { outline: 2px solid orange; }
</style>
typescript
import type { BeatTrack } from 'ez-web-audio'
import { createBeatTrack } from 'ez-web-audio'

export function mountKick(root: HTMLElement, sampleUrl: string): () => void {
  let track: BeatTrack | undefined
  let removed = false
  let playing = false
  const pattern = Array.from({ length: 16 }, (_, index) => index % 4 === 0)
  const play = document.createElement('button')
  play.type = 'button'
  play.textContent = 'Play'
  const status = document.createElement('output')
  root.append(play, status)

  const cells = pattern.map((active, index) => {
    const cell = document.createElement('button')
    cell.type = 'button'
    cell.textContent = String(index + 1)
    cell.setAttribute('aria-pressed', String(active))
    cell.onclick = () => {
      pattern[index] = !pattern[index]
      cell.setAttribute('aria-pressed', String(pattern[index]))
      if (track)
        track.beats[index].active = pattern[index]
    }
    root.append(cell)
    return cell
  })

  play.onclick = async () => {
    if (!track) {
      play.disabled = true
      status.textContent = ''
      try {
        const kick = await createBeatTrack([sampleUrl], { numBeats: cells.length })
        if (removed) {
          kick.dispose()
          return
        }
        track = kick
        track.setPattern(pattern)
        track.on('beat', ({ detail }) => {
          cells.forEach((cell, i) => cell.classList.toggle('current', i === detail.beatIndex))
        })
      }
      catch (error) {
        status.textContent = error instanceof Error ? error.message : 'Could not load kick'
        return
      }
      finally {
        play.disabled = false
      }
    }

    if (playing) {
      track.stop()
      cells.forEach(cell => cell.classList.remove('current'))
    }
    else {
      track.playActiveBeats(120, 1 / 16)
    }
    playing = !playing
    play.textContent = playing ? 'Stop' : 'Play'
  }

  return () => {
    removed = true
    track?.dispose()
    root.replaceChildren()
  }
}

Call mountKick(document.getElementById('kick')!, '/audio/drum-samples/kick1.wav') after the container exists. Keep the function it returns and call it when you remove the instrument. Disposing the track stops its scheduler, releases its samples and detaches its event listeners.

How the playhead follows the sound ​

playActiveBeats() schedules hits ahead on the audio clock. BeatTrack dispatches the corresponding beat events when that clock reaches the scheduled time. The handler can paint the column directly from event.detail.beatIndex. The UI uses the index reported by the scheduler, so it does not need its own timer or step counter.

The three-lane demo listens to the kick track for its playhead. Each lane stores its own pattern, so clicking a snare cell changes the snare’s next pass without moving the highlight. To change tempo while the machine runs, call setTempo(bpm) on each standalone track.

See Also ​