使用滑块控制音频

Control audio with a slider

当用户在自定义音频播放器(首选 Vanilla JS)中向上或向下拉音量进度时,如何通过鼠标操作控制音量

您可以将 input 元素与 type="range" 一起使用,然后侦听 input 事件或 change 事件以更新音量。 change 事件将在用户停止移动滑块时触发。 input 事件将在滑块移动时触发。

示例:

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>