Stop an audio that was created throught javascript

Viewed 60

Here's roughly what my script looks like.

var ButtonSelect = document.querySelectorAll(".musicBtn")

ButtonSelect.forEach(element => element.addEventListener("click", playMusic))

function playMusic(){
    var audio = new Audio("music1.mp3");
    if (this.id == "A")
        audio.play();
    else if (this.id == "B") {
        audio.src="music2.mp3";
        audio.play();
    } else if (this.id == "C") {
        audio.src="music3.mp3";
        audio.play();
    } ...
}

And it pretty much goes on like this. So, depending on which button is pressed, a different song plays. But I want to make it so that not only does pressing a button start the corresponding song, but it must also stop whatever song is currently playing. Since the audio object is created locally and disappears after the function call, how do I go about that? Isn't there any way to just ask the page to stop whatever sound is playing without specifying where it comes from?

1 Answers

The question asks how the currently playing audio can be paused when a new one is selected.

There is an additional problem. The given code creates a new element each time a button is pressed but it never gets rid of it so gradually store will fill up with audio elements that are never going to be revisited.

A simple way of getting round this is to have just one audio element and change the src when a button is clicked. That way we are not building up elements that subsequently become redundant.

Try this code first of all:

var ButtonSelect = document.querySelectorAll(".musicBtn")
var audio = new Audio("music1.mp3");

ButtonSelect.forEach(element => element.addEventListener("click", playMusic))

function playMusic(){
    audio.pause();
    if (this.id == "A") {
        audio.src="music1.mp3";
        audio.play();
    }
    else if (this.id == "B") {
        audio.src="music2.mp3";
        audio.play();
    } else if (this.id == "C") {
        audio.src="music3.mp3";
        audio.play();
    }
}

If that works OK you could consider simplifying your code, for example by having the audio source as a data-src attribute in each of your buttons rather than having to sort out which audio to play via an id.

Related