MDN self-hosted library · e01.org

Using the Web Audio API

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

js
const audioContext = new AudioContext();
html
<audio src="myCoolTrack.mp3"></audio>
js
// get the audio element
const audioElement = document.querySelector("audio");

// pass it into the audio context
const track = audioContext.createMediaElementSource(audioElement);
html
<button data-playing="false" role="switch" aria-checked="false">
  <span>Play/Pause</span>
</button>
js
track.connect(audioContext.destination);
js
// Select our play button
const playButton = document.querySelector("button");

playButton.addEventListener("click", () => {
  // Check if context is in suspended state (autoplay policy)
  if (audioContext.state === "suspended") {
    audioContext.resume();
  }

  // Play or pause track depending on state
  if (playButton.dataset.playing === "false") {
    audioElement.play();
    playButton.dataset.playing = "true";
  } else if (playButton.dataset.playing === "true") {
    audioElement.pause();
    playButton.dataset.playing = "false";
  }
});
js
audioElement.addEventListener("ended", () => {
  playButton.dataset.playing = "false";
});
js
const gainNode = audioContext.createGain();
js
track.connect(gainNode).connect(audioContext.destination);
html
<input type="range" id="volume" min="0" max="2" value="1" step="0.01" />
js
const volumeControl = document.querySelector("#volume");

volumeControl.addEventListener("input", () => {
  gainNode.gain.value = volumeControl.value;
});
js
const pannerOptions = { pan: 0 };
const panner = new StereoPannerNode(audioContext, pannerOptions);
html
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01" />
js
const pannerControl = document.querySelector("#panner");

pannerControl.addEventListener("input", () => {
  panner.pan.value = pannerControl.value;
});
js
track.connect(gainNode).connect(panner).connect(audioContext.destination);