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>
If you are trying to stop the current audio playing and play new audio data. How about the solution below: Just call the stopAllAudio() function before playing the next audio and all audio playing prior should stop.
function stopAllAudio() {
var sounds = document.getElementsByTagName('audio');
for (i = 0; i < sounds.length; i++) sounds[i].pause();
};