Skip to content

Why Timing Drifts ​

Play the three-note sequence below. Each note starts half a second after the previous one, even when the samples take longer than that to download on the first click.

Quick Reference ​

MethodWhen the sound starts
sound.play()As soon as the audio context is ready
sound.playIn(1)One second from the current audio time
sound.playAt(start)At the given time in seconds on the audio clock

Why audio scheduling needs the audio clock.

1. Play Now

Immediate playback with play()


2. Play In 1 Second

Delayed playback with playIn(seconds)


3. Schedule 3 Notes

Precise timing with playAt(audioContext.currentTime + offset)

audio clock (locked)
0s
0.5s
1s

4. Perfect Sync

Multiple sounds starting at exact same time with playAt()

Why Timing Matters ​

A JavaScript timer can run late when the main thread is busy or the browser throttles a background tab. Once you submit a future start time to Web Audio, the audio engine can play the note while JavaScript is busy. The clock pauses when the audio context is suspended.

Read AudioContext.currentTime after the context is running and the samples have decoded. A timestamp captured before a slow download can already be in the past by the time you call playAt(). Several overdue notes can then sound together.

Immediate Playback ​

Call playClick() from a click or tap handler so the browser can activate audio. Pass the URL of a sample your app serves. You can use a copy of the demo click.

typescript
import { createSound } from 'ez-web-audio'

export async function playClick(url: string, delaySeconds = 0) {
  const click = await createSound(url)
  click.once('end', () => click.dispose())
  if (delaySeconds > 0)
    click.playIn(delaySeconds)
  else
    await click.play()
  return click
}

Delayed Playback ​

Call playClick(url, 1) to schedule the click one second after loading finishes. Pass 0.5 for half a second. To cancel a pending click, call dispose() on the returned sound.

Scheduled Playback ​

For a drum pattern, prepare one voice per scheduled hit. Scheduling a second hit on the same Sound retriggers that voice. Here the two kick hits and the two hi-hat hits each have their own instances, even though each pair shares a sample URL.

typescript
import { createSounds, getAudioContext } from 'ez-web-audio'

export async function preparePattern(kickUrl: string, snareUrl: string, hatUrl: string) {
  const hits = await createSounds([kickUrl, hatUrl, snareUrl, hatUrl, kickUrl])

  return {
    async play() {
      const ctx = await getAudioContext()
      const start = ctx.currentTime + 0.05
      await Promise.all(hits.map((sound, i) => sound.playAt(start + i * 0.25)))
    },
    dispose() {
      hits.forEach(sound => sound.dispose())
    },
  }
}

On the first press, await preparePattern() with URLs for your kick, snare, and hi-hat, then call the returned object's play(). The 50 ms lead gives the browser time to submit all five notes before the first hit. Keep the object for replay and call dispose() when removing the instrument.

Perfect Synchronization ​

For a chord, give every voice the same start and stop times. This C major chord sounds for one second. Both times go to the audio engine as soon as the voices are ready.

typescript
import { createOscillator, getAudioContext } from 'ez-web-audio'

export async function playChord() {
  const ctx = await getAudioContext()
  const voices = await Promise.all([261.63, 329.63, 392].map(frequency =>
    createOscillator(ctx, { frequency, type: 'triangle', gain: 0.2 }),
  ))
  const start = ctx.currentTime + 0.05
  await Promise.all(voices.map(async (voice) => {
    voice.once('end', () => voice.dispose())
    await voice.playAt(start)
    await voice.stopAt(start + 1)
  }))
  return voices
}

Call playChord() from a button handler. Each voice releases its resources at the end of the note. To silence the chord early, call dispose() on each returned voice.

API Used ​

playAt(time) resolves when the library has submitted the start time. To schedule a stop, pass a second absolute timestamp to stopAt(time). For a sample that should play to its natural end, listen for its end event.

Next Steps ​