Play the second track while previous one is stopping (variable code in JS?!)

I have a couple tracks that is programmed by JavaScript. Just One problem that I need to fix and this is when I play one track is working fine and then when I want to play the other track. I want to stoped the first one and then play the other one.

const audioPlayers = document.querySelectorAll(".audio-player");

audioPlayers.forEach((audioPlayer) => {
  const audioUrl = audioPlayer.dataset.url;
  const audio = new Audio(audioUrl);
  .
  .
  .audio.onplay = () => audioPlayer.classList.add("playing");
    audio.onpause = () => audioPlayer.classList.remove("playing");
    audio.onloadeddata = () => audioPlayer.classList.remove("loading");
    // audio.ondurationchange = showTimeDuration;
    audio.onended = () => (audio.currentTime = 0);
    audio.ontimeupdate = () => {
      const { currentTime } = audio;
      const currentTimeDisplay = formatTimeToDisplay(currentTime);
      updateCurrentTimeDisplay(currentTimeDisplay);
      updateCurrentPercent();
      if (currentTime === 0) {
        showTimeDuration();
      }
    };
  }

  start();
});
<div class="audio-player" data-url="sound/1.mp3" dir="ltr">
  <div class="player">
    <button type="button" class="btn-play">
      <span class="material-icons icon-play">play_arrow</span>
      <span class="material-icons icon-pause">pause</span>
      <span class="material-icons icon-loop">loop</span>
      <span class="material-icons icon-error">error_outline</span>
    </button>

Since there are several things you handle when you click “play” on an audio element, it would be better idea to create a function to handle that. In that function you can do stuff like add the “playing” class, as i see is part of your app design, ofc make the element play and to follow your desire, to make sure no other element is currently playing(stop it, if there is such). Its might be easy to identify such element by targeting the “playing” class with query selector and pause/stop the audio of that element, as well as remove the class off it(assuming only one element is to be playing at any time). You should also be careful of the order in which you run the different actions. Have it clearly thought in your head and even write down on a note, whats to be done after what. For example- look if there is element “playing”, stop/pause that element and remove the class, add the class to the current element that has been clicked, make the element play.

2 Likes

Thanks for you explanation.
Could you please take an example…
here’s my work

I added this
but still doesn’t work ! :frowning:

 window.addEventListener("play", function(evt)
 {
     if(window.$_currentlyPlaying)
     {
         window.$_currentlyPlaying.pause();
     } 
     window.$_currentlyPlaying = evt.target;
 }, true);

sorry but im not experienced with working with audio players and it will take me a while to decipher your code and apply what i suggested.

I’ve tried this code and above code separately in my JS but still doesn’t work!

document.addEventListener('play', function(e){
    var audios = document.getElementsByTagName('audio');
    for(var i = 0, len = audios.length; i < len;i++){
        if(audios[i] != e.target){
            audios[i].pause();
        }
    }
}, true);

why dont you try

let currentlyPlaying=document.querySelector(".playing")
if (currentlyPlaying) {
  currentlyPlaying.pause()
  currentlyPlaying.classList.remove("playing")
}

Assuming your code makes sure if there is playing audio, it has the “playing” class

1 Like

Thanks for your kindness and supporting
unfortunately doesn’t work
I can understand why is not working

  const playBtn = audioPlayer.querySelector(".toggle-play");
  playBtn.addEventListener(
    "click",
    () => {
      if (audio.paused) {
        playBtn.classList.remove("play");
        playBtn.classList.add("pause");
        audio.play();
      } else {
        playBtn.classList.remove("pause");
        playBtn.classList.add("play");
        audio.pause();
      }
    },
    false
  );
    // stop
    let currentlyPlaying=document.querySelector(".playing")
    if (currentlyPlaying) {
      currentlyPlaying.pause()
      currentlyPlaying.classList.remove("playing")
    }

<div class="play-container">
      <div class="toggle-play play"></div>
    </div>
    <div class="timeline">
      <div class="line">
        <input dir="ltr" type="range" min="0" max="100" value="0">
      </div>
      <div class="data">
        <div class="current-time"></div>
        <div class="divider">&nbsp;/&nbsp;</div>
        <div class="time">
        <div class="length"></div>
        </div>
      </div>