Reputation: 3
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 🥁 Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
<script src="index.js"></script>
</body>
Upvotes: 0
Views: 77
Reputation: 719
Without the HTML it's difficult to say. But it seems like the number of items returned by document.querySelectorAll(".drum")
is greater than the number of items in playlist
. So eventually you run out of playlist
items and audio.src
is assigned the value undefined.
Upvotes: 1