0
votes

I'm trying to make a volume slider for each audio player (like 4 volume sliders for 4 audio players) something like https://deepfocus.io/ , so far and thanks to deepak I have a code that can play/pause and change volume of different audio players. But I would like to replace play and pause written buttons by play and pause images, Here is the code:

Javascript:

$('.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;
};

HTML:

<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>

PS: I don't know anything about Javascript, thank you in advance!

1

1 Answers

1
votes

In your case just use img instead of button and with jquery toggle the source of the image:

$('.button').click((e) => {
  var _this = e.target;
  var id = _this.id;
  if (!$(_this).hasClass('play')) {
    $(_this).attr('src', 'https://image.freepik.com/free-icon/pause-button_318-30027.jpg');
    document.getElementById(`sound${id}`).play();
  } else {
    $(_this).attr('src', 'https://image.freepik.com/free-icon/play-alt_318-2156.png');
    document.getElementById(`sound${id}`).pause();
  }

  $(_this).toggleClass('play');
})

function setVolume(id, value) {
  var audio = document.getElementById(`sound${id}`);
  audio.volume = value / 100;
};
img {
  width: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <img class="button" src="https://image.freepik.com/free-icon/play-alt_318-2156.png" id="1" />
  <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>
  <img class="button" src="https://image.freepik.com/free-icon/play-alt_318-2156.png" id="2" />
  <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>