Search code examples
javascriptaudioaddeventlistener

addEventListener always creates a new audio element, due to which i am unable to pause my once played audio


I have created a click event listener then added a function in it which conatin some parameters, according to that parameters i am creating an audio element, which i play in further steps. Problem arises when i wish to pause that same audio after detecting another click, it never happens because it creates a new audio element on every click with same values and pause it, although that new audio element was never played and the first audio element created keeps playing.

let check = true;
masterPlayButton.addEventListener("click", function (i) {
  minorPlayPause(i);
});
function minorPlayPause(x) {
  let audio = new Audio("songs/" + x + ".mp3");
 if (check == true) {
    check = false;
    audio.play();
    };
  } else {
    check = true;
    audio.pause();
  }
}

I tried creating audio element outside the event listener so that everytime a new audio element is not created but it doesnt work because i want to create audio element according to the parameters provided from click data. Also, i tried to put another event listener inside the 'if' (as written in the provided code) to detect the pause on the same audio element, but it didnt worked. I just want to pause the same audio on second click.

A helping hand is most appreciable !!


Solution

  • "Problem arises when I wish to pause that same audio after detecting another click, it never happens because it creates a new audio element on every click".

    A new audio object is created on every click because your code says to create a new audio object on every click:

    function minorPlayPause(x) {
      let audio = new Audio("songs/" + x + ".mp3");
      // more code
    }
    

    If you only want to create a new audio object when one is not currently playing then you need to move the let audio = new ... line into the conditional:

    function minorPlayPause(x) {
      if (check == true) {
        let audio = new Audio("songs/" + x + ".mp3");
        check = false;
        audio.play();
      } else {
        check = true;
        audio.pause();
      }
    }
    

    You will also need to store the old audio object somewhere so that you can access it later in order to pause it.

    function minorPlayPause(x) {
      if (check == true) {
        let audio = new Audio("songs/" + x + ".mp3");
        check = false;
        audio.play();
        oldAudio = audio // could make this a global variable, or return it from this function
      } else {
        check = true;
        oldAudio.pause();
      }
    }