I've been working on creating a Drum Kit website. My approach involves using an array to hold all the sound files, and using a loop to call the play() function. However, I encountered an issue when trying to load the sounds - the debug console showed: "Uncaught DOMException DOMException: Failed to load because no supported source was found."
The strange thing is that when I replace "audio.src = playlist[i];" with "audio.src = playlist[1];", the website successfully locates the file source and plays the selected sound. But if I change [1] to [i], it fails to locate the source file. Why does this happen?
Have you experienced a similar behavior in JavaScript before? While I can find alternative ways to make the website function correctly, this particular problem has been lingering in my mind.
Below are snippets of my Javascript code:
var audio = new Audio();
var playlist = ["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 part of the HTML structure:
<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>