Is there a way to change volume of <audio> in real time?

58 Views Asked by At

I'd like to adjust the volume of an autoplaying, looping mp3 track based on the user's scroll position. I don't see any way to adjust the volume of the track playing, however. Is there a way to use JS, perhaps, to change the audio's volume?

I've looked through the tag's attributes, but the closest I could find was 'muted.' Do I need to use something like the Web Audio API instead?

1

There are 1 best solutions below

0
AKX On BEST ANSWER

See: HTMLMediaElement.volume. HTMLAudioElement (the interface for <audio>) inherits from HTMLMediaElement.

// Fade in the audio over the first 500 pixels of the document.
document.addEventListener("scroll", () => {
  document.querySelector("audio").volume = window.scrollY / 500;
});