Search code examples
javascripthtmlaudiohtml5-audio

Volume slider for every audio player in HTML5 and JavaScript


I'm trying to make a volume slider for each audio player (like 4 volume sliders for 4 audio players), so far I found a code source of a volume slider for only audio player, and to be honest, I don't know anything about javascript and you guys are my last hope. Here is what I found so far.

HTML:

<button id="btn1">Play</button>
<audio id="sound1" loop>
<source src="assets/audio/rain.mp3" type="audio/mpeg"/>
</audio>
<input id="sound1" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>
</div>
<div>
<button id="btn2">Play</button>
<audio id="sound2" loop>
<source src="assets/audio/music.mp3" type="audio/mpeg"/>
</audio>
<input id="sound2" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>
</div>

JAVASCRIPT:

$('.play').click(function(){
    var $this = $(this);
    var id = $this.attr('id').replace(/btn/, '');
    $this.toggleClass('active');
    if($this.hasClass('active')){
        $this.text('Pause'); 
        $('audio[id^="sound"]')[id-1].play();        
    } else {
        $this.text('Play');
        $('audio[id^="sound"]')[id-1].pause();
    }
});


var audio = document.getElementById('sound1');
var volumeControl = document.getElementById('sound1');

var setVolume = function(){
    audio.volume = this.value / 100;
};

volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);

Solution

  • Here is working example for you.

    1. setVolume is lowerCase you were using SetVolume.
    2. Technique to call audio needs to improve.I have done.

    $('.play').click((e) => {
      var _this = e.target;
      var id = _this.id;
      $(_this).toggleClass('active');
      if ($(_this).hasClass('active')) {
        $(_this).text('Pause');
        document.getElementById(`sound${id}`).play();
      } else {
        $(_this).text('Play');
        document.getElementById(`sound${id}`).pause();
      }
    })
    
    function setVolume(id, value) {
      var audio = document.getElementById(`sound${id}`);
      audio.volume = value / 100;
    };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <button class="play" id="1">Play</button>
      <audio id="sound1" loop>
    <source src="https://www.partnersinrhyme.com/files/sounds1/MP3/ambience/oceansrfs/SEASHORE.mp3" type="audio/mpeg"/>
    </audio>
      <input type="range" min="0" max="100" step="1" onchange="setVolume(1, this.value)" />
    </div>
    <div>
      <button class="play" id="2">Play</button>
      <audio id="sound2" loop>
    <source src="https://rainymood.com/audio1112/0.m4a" type="audio/mpeg"/>
    </audio>
      <input type="range" min="0" max="100" step="1" onchange="setVolume(2,this.value)" />
    </div>