How can I stop my audio from looping in an if-else statement?

Viewed 33

The audio is playing in a loop as per the if statement, but it is not pausing as per the else statement. Why is this happening?

I also tried:
if(...) { ... } else if(...) { ... }
because if I use else on its own then nothing works.

What am I doing wrong?

Here is my code:

    function loop(){
        var audio1 = new Audio('./sounds/tom-1.mp3');
        var input1 = document.getElementById('input1');
        if(input1.checked == true) {
            audio1.play();
            audio1.loop = true;
        } else if (input1.checked == false) {
            audio1.pause();
            audio1.loop = false;
        }
    }

And the HTML:

    <label class="switch">
        <input type="checkbox" id="input1" onclick="loop()">
        <span class="slider round"></span>
    </label>
1 Answers

You are creating new Audio every time you click, so you are pausing a new one, not the one that is currently playing.

let audio;
function loop() {
  if (!audio) {
    audio = new Audio("./sounds/tom-1.mp3");
  }
  let input1 = document.getElementById("input1");
  if (input1.checked == true) {
    audio.play();
    audio.loop = true;
  } else if (input1.checked == false) {
    audio.pause();
    audio.loop = false;
  }
}

P.S.

Remember to never use var

Related