0

When I click on the first button, the winter audio is loaded but when I click on summer, both work together. How can I make winter audio stop when I click on other buttons? I am working on a relaxing-music web app. I may end up having about 20 or 30 music files. How can I make one file stop when I click play on the other?

document.getElementById('winter').onclick =  function changeBackground() {
document.body.style.backgroundImage = "url('winter.jpg')"
        var audio = new Audio('winter.mp3');
        audio.play();
}
document.getElementById('summer').onclick =  function changeBackground() {
    document.body.style.backgroundImage = "url('summer.jpg')"
    var audio = new Audio('summer.mp3');
    audio.play();
}

1 Answers1

0

Your implementation is done pooly, because you're creating a new Audio() on a changeBackground method. So this will create a new audio every time the click event is fired.

But to answer your question, To stop an audio you must use pause() method which is defined in the Audio API.

Here's an example:

// First create the audios
var audioElements = document.querySelectorAll(".audio");
var audioObj = {};

// Create audios for each element
audioElements.forEach((el, i)=>
{
  audioObj[el.getAttribute("data-name")] = new Audio((el.getAttribute("data-name") + ".mp3"));
});

// Methods to operate those audios
function playAudio(el)
{
  var audioName = el.getAttribute("data-name");
  // Create audios for each element
  Object.keys(audioObj).forEach((keyName, i)=>
  {
    if(audioName != keyName)
    {
      audioObj[keyName].pause();
      return;
    }

    audioObj[audioName].play();
    console.log(audioName);
    document.body.style.backgroundColor = audioName.concat(".png");
  });
}

function changeBackground(imageSource)
{
  document.body.style.backgroundImage = `url(${imageSource})`;
}
<button data-name="winter" class="audio winter" onclick="return playAudio(this)">Play Winter</button>
<button data-name="summer" class="audio summer" onclick="return playAudio(this)">Play Summer</button>
<button data-name="spring" class="audio spring" onclick="return playAudio(this)">Play Spring</button>

So in your case, you could pause() all other videos when another is clicked. I have done this only to control two audios.

Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24
  • Thanks, what if i have more than that? Maybe 20 files or something. Is there any other way I can do that than repeating the lines in every function? – Ahmad Fathy Aug 12 '20 at 09:02
  • I only worked with what you gave me. Let me change the code and make it work with any number of audios. – Mosia Thabo Aug 13 '20 at 11:08