-1

I'm new at JS

I'm making a drum kit website and i create a switch section but it's not working.

var numberOfDrumButtons = document.querySelectorAll(".drum").length;

for (var i = 0; i < numberOfDrumButtons; i++) {

  document.querySelectorAll(".drum")[i].addEventListener("click", function() {


    var buttonInnerHtml = this.innerHTML;

    switch (buttonInnerHtml) {
      case "w":
        var tom1 = new Audio('songs/oni-chan.mp3');
        tom1.play();
        break;

      case "a":
        var tom2 = new Audio('songs/oni-chan2.mp3');
        tom2.play();
        break;

      case "s":
        var tom3 = new Audio('songs/oni-chan3.mp3');
        tom3.play();
        break;
      default:
        break;
    }

  })
}    
    

HTML:

  <div class="set">
    <button class="w drum"><span>w</span></button>
    <button class="a drum"><span>a</span></button>
    <button class="s drum"><span>s</span></button>
    <button class="d drum"><span>d</span></button>
    <button class="j drum"><span>j</span></button>
    <button class="k drum"><span>k</span></button>
    <button class="l drum"><span>L</span></button>
  </div>

  <script src="index.js" href="UTF-8"></script>
CascadiaJS
  • 2,320
  • 2
  • 26
  • 46
Yunus
  • 1
  • 6

1 Answers1

2

From the Audio docs(https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#determining_when_playback_can_begin):

There are three ways you can tell when enough of the audio file has loaded to allow playback to begin:

  • Check the value of the readyState property. If it's HTMLMediaElement.HAVE_FUTURE_DATA, there's enough data available to begin playback and play for at least a short time. If it's HTMLMediaElement.HAVE_ENOUGH_DATA, then there's enough data available that, given the current download rate, you should be able to play the audio through to the end without interruption.

  • Listen for the canplay event. It is sent to the element when there's enough audio available to begin playback, although interruptions may occur.

  • Listen for the canplaythrough event. It is sent when it's estimated that the audio should be able to play to the end without interruption. The event-based approach is best:

myAudioElement.addEventListener("canplaythrough", event => {
  /* the audio is now playable; play it if permissions allow */
  myAudioElement.play();
});
Daruda
  • 167
  • 3