I'm trying to code a playlist. I'd like to start an audio when the title of the audio is clicked. For now it works, but when I click a title and then others, previous songs clicked are not stopped so they are all playing at the same time. Here is my html :
<div class="audio" onclick=
"playAudio('algebrasuicide_fathersbythedoor.wav')">
algebra suicide father by the door
</div>
<div class="audio"onclick=
"playAudio('algebrasuicide_inbedwithboys.wav')">
algebra suicide in bed with boys
</div>
<div class="audio"onclick=
"playAudio('aprilmagazine_parade.wav')">
april magazine parade
</div>
and this is my js :
function playAudio(src) {
new Audio(src).play();
}
I'm a novice, I know the answer is probably very simple but I tried a lot of things and nothing worked.
I hope someone here can help me ! Thank you :)
The simplest would be to keep a reference to the current audio (if any) and .pause()
it.
let audio;
function pauseAudio() {
// If audio is not undefined and if is playing, pause it
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0; // Rewind track to beginning (if needed?)
}
}
function playAudio(src) {
pauseAudio(); // Pause any currently playing
audio = new Audio(); // Save a reference
audio.src = src;
audio.play();
}
Also, stop using inline JS on*
handlers in HTML. JavaScript should be in one place only and that's its respective tag of file.
Instead:
<button type="button" data-audio="lorem.wav">Lorem</button>
<button type="button" data-audio="ipsum.wav">Ipsum</button>
<button type="button" data-audio="dolor.wav">Dolor</button>
let audio;
function pauseAudio() {
// If audio is not undefined and if is playing, pause it
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0; // Rewind track to beginning (is you need this)
}
}
function playAudio(src) {
pauseAudio(); // Pause any currently playing
audio = new Audio(); // Save a reference
audio.src = src;
audio.play();
}
document.querySelectorAll("[data-audio]").forEach((elAudioBtn) => {
const src = elAudioBtn.dataset.audio;
playAudio(src);
});
Find out more about: data-* attributes.