Home > Enterprise >  Can't play sound from an array using Javascript
Can't play sound from an array using Javascript

Time:02-03

I'm trying to create a Drum Kit website. I use array as a placeholder to all the sound files, and use loop to call the play() function. When I try to load, the debug consol said: "Uncaught DOMException DOMException: Failed to load because no supported source was found."

The problem is that if I replace "audio.src = playlist[i];" by "audio.src = playlist[1];", the website can locate the source of the file & play the selected sound. But if I replace [1] by [i], the website can't locate the source file. So why is it?

Do you know why Javascript behaves this way? I can find another way to get the website to work but this thing has been tickling in my mind for a while.

Below is my Javascript codes:

var audio = new Audio();

var playlist = new Array("sounds/crash.mp3","sounds/kick-bass.mp3","sounds/snare.mp3","sounds/tom-1.mp3","sounds/tom-2.mp3","sounds/tom-3.mp3","sounds/tom-4.mp3");

var drum = document.querySelectorAll(".drum")

for (var i = 0; i < drum.length; i  ) {
        drum[i].addEventListener("click", play);
        function play() {
            audio.src = playlist[i];
            audio.play();       
            }
    }

Below is the HTML:

<body>

  <h1 id="title">Drum            
  • Related