Having trouble with playing audio from an array in Javascript

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>

Answer №1

It's challenging to determine without the HTML provided, but it appears that there is a discrepancy between the number of elements returned by

document.querySelectorAll(".drum")
and the items in the playlist. This results in depleting the items in the playlist, leading to assigning an undefined value to audio.src.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Personalizing the look of Stripe Payment Component in a React Application

Currently, I have integrated the Stripe Payment Element into my React application using the code snippet below: import { useStripe, useElements, PaymentElement, } from '@stripe/react-stripe-js' export const PaymentDetails = () => { const st ...

React and Redux: The Search for Missing Props

I am embarking on a new project using a different technology stack for the first time. In my previous job, I inherited an existing project with everything already set up. However, I am facing issues as my props are coming up as undefined and I am unsure wh ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Tips on avoiding duplicate selection of checkboxes with Vue.js

Recently delving into vue.js, I encountered a challenge with multiple checkboxes sharing the same value. This resulted in checkboxes of the same value being checked simultaneously. How can this issue be resolved? var app = new Vue({ el: '#app&apo ...

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

When examining passwords, Bcrypt returns false

In my application, I am utilizing the Promise interface along with bcrypt. Despite using the same password for comparison, I am receiving a false result. const bcrypt = require('bcrypt'); const saltRounds = 10; const password = 'secret&ap ...

Show a variety of logos on the website based on the current date

I've been experimenting with displaying a unique logo on my website based on the current date (for example, showing a Christmas-themed logo during December). Here's what I have so far: <img class="logo" id="global_logo" sty ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

Leverage Axios in React to dynamically fetch and display real-time data

Executing an Axios get request in order to retrieve data and display it using React. export function Wareh() { const [wareh, setWareh] = useState([{}]); useEffect(() => { axios.get("http://localhost:1515/wareh").then((response) => ...

Can you explain the contrast between `/:foo*` and `/:foo(.*)` when used in express routes?

When using Express, it is possible to define endpoints with different paths: app.get('/:foo*', function(req, res) { ... }); app.get('/:foo(.*)', function(req, res) { ... }); Although these two paths may appear similar, what sets them ...

Interference in the output of .innerHTML leads to disruption

I have been working on a feature to display a calculated price based on the selected quantity for each individual product. I attempted to duplicate the code and modify variable names, but encountered issues with the increase/decrease buttons triggering mul ...

JavaScript makes it easy to streamline conditions

Can someone help me simplify this repetitive condition? if (this.get('fileUrl')) { const isUnsplash = this.get('fileContainer.asset_kind') === 'UnsplashAsset'; return Asset.create({ url: this.get('f ...

What could be causing node.appendChild() to malfunction?

I need some help with a piece of code that I'm working on for a calendar application. The code is meant to dynamically generate and display dates for the current month using ReactJS. However, I keep encountering an error that says "appendChild is not ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

Ensure that the initial section of the page spans the full height of the browser, while all subsequent sections have a

I have a website composed of various blocks with different heights, all extending to full width. My goal is to make the first block the full height and width of the browser window, while keeping the other blocks at a set height as seen on this site: After ...

Is it possible to apply the DRY Concept to this React JS code?

https://i.stack.imgur.com/jcEoA.png import React from "react"; import { Chip, Box } from '@mui/material'; const Browse = () => { const [chip, setChip] = React.useState("all" ...

In Redux, it is possible to add characters to an array but for some reason the remove action does not successfully reach the reducer

As a user types or erases characters, I am utilizing redux to update an array of characters. This allows me to set a success flag when the user correctly types the entire phrase. Currently, when typing in characters, the SET_INPUT action in redux fires of ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...