Search code examples
javascriptaudiovolumeaudio-player

Control audio with a slider


How to control volume with mouse action when user pull the volume progress up or down in a custom made audio player (Vanilla JS preferred)


Solution

  • You can use an input element with type="range", then listen for the input event or change event to update the volume. The change event will fire when the user stops moving the slider. The input event will fire as the slider is being moved.

    Example:

    let audio = new Audio("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");
    
    // update the volume when the slider is moved
    volume.addEventListener("input", (e) => {
      audio.volume = e.currentTarget.value / 100;
    });
    
    play.addEventListener("click", (e) => {
      return audio.paused ? audio.play() : audio.pause();
    });
    <input type="range" id="volume" value="100">
    <button type="button" id="play">
    Play/Pause Audio
    </button>