MDN self-hosted library · e01.org

Web Audio API best practices

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const button = document.querySelector("button");
button.addEventListener("click", () => {
  const audioCtx = new AudioContext();
  // Do something with the audio context
});
js
const audioCtx = new AudioContext();
const button = document.querySelector("button");

button.addEventListener("click", () => {
  // check if context is in suspended state (autoplay policy)
  if (audioCtx.state === "suspended") {
    audioCtx.resume();
  }
});
js
gainNode.gain.value = 0.5;
js
gainNode.gain.setValueAtTime(1, audioCtx.currentTime + 2);