Intermittently play a series of sound files, with only the final sound ringing out

My goal is to create an app that plays a sound based on a number input. I have several short MP3 audio files for different numbers, and I want the app to play these sounds in sequence. However, when I try to do this, only the last sound corresponding to the final number is played, and I encounter an error message in the console:

"Uncaught (in promise) DOMException: The play() request was interrupted by a new load request."

I'm unsure of what I am missing or if it's even possible to achieve this. Any assistance would be greatly appreciated.

function playSound(note){

    var currentPlayer;
    var player = document.getElementById("player");

    var isPlaying = player.currentTime > 0 && !player.paused && !player.ended 
&& player.readyState > 2;


     if (!isPlaying){

        player.src = "sounds/"+note+".mp3";
        player.play();

     }else{
        player.pause();
        player.currentTime = 0;
        currentPlayer = player;

     }



}


//variable with numbers where each number should load a sound and play
var numString = "0934590042529689108538569377239609480456034083552";


for(i = 0; i < numString.length; i++){


    switch (parseInt(numString[i])){
        case 1:
            playSound("C"); 
            break;
        case 2:
            playSound("D");
            break;
        case 3:
            playSound("E");
            break;
        case 4:
            playSound("F");
            break;
        case 5:
            playSound("G");
            break;

        case 6:
            playSound("A");
            break;

        case 7:
            playSound("B");
            break;

        case 8:
            playSound("C2");
            break;

        case 9:
            playSound("D2");
            break;


        case 0:
            playSound("silence");
            break;


}

The Html:

<audio controls id="player" style="display: none">
    <source  src="#"></source>
</audio>

Answer №1

Before you can load the next note, you must allow the first one to finish playing:

var index = 0;
var numString = "0934590042529689108538569377239609480456034083552";
var notes = ['silence', 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'C2', 'D2'];
var player = document.getElementById('player');

function playNote() {
  if (index >= numString.length) {
    stop();
    return;
  }
  var note = notes[Number(numString[index])]; // convert number to corresponding note ('1' => 'C')
  if (!note) {
    stop();
    return;
  }
  index++;
  player.src = `sounds/${note}.mp3`;
  player.play();
}

function stop () {
  player.removeEventListener('ended', playNote);
}

player.addEventListener('ended', playNote);
playNote();

Edit:

I have replaced this with player in the playNote function. When playNote() is initially called, there is no this object referring to the player. It should have been playNote.call(player), but it currently works as is.

To minimize the load times between notes, you have two options:

Load sound files separately using multiple audio elements

Create a new Audio() for each note and load the sound file:

var numString = "0934590042529689108538569377239609480456034083552";
var notes = ['silence', 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'C2', 'D2'];
var audios = {};
notes.forEach(note => {
  var audio = new Audio();
  audio.src = `sounds/${note}.mp3`;
  audios[note] = audio;
});

var currentAudio = null;

function playNote () {
  if (currentAudio) {
    currentAudio.removeEventListener('ended', playNote);
  }
  if (index >= numString.length) {
    return;
  }
  var note = notes[Number(numString[index])];
  if (!note) {
    return;
  }
  currentAudio = audios[note];
  index++;
  currentAudio.play();
  currentAudio.addEventListener('ended', playNote);
}

playNote();

Utilize the AudioContext API

The new Web Audio API is more intricate than new Audio() but offers greater capabilities. You can generate various sounds without needing every file on your server by leveraging the client's sound processing abilities.

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

The type of jQuery selector

I came across jQuery code that looks like this return 13 == t.keyCode ? (t.preventDefault(), !1) : void 0 Can someone explain what the ? and : mean in this context? Please provide a reference for further reading, as I am still new to jQuery. Thank you ...

What is the solution to the question: "Hey there, time traveler. We are currently in an era where CSS prefixes are no longer necessary, thanks to the advances in prefix-less CSS

I'm having an issue in my Next.JS app with importing my stylesheet in _app.js. Here is how I currently import it: import '../public/css/Index.css'; The content of Index.css looks like this: .index-container { margin: 20px auto 0; } Wha ...

A JavaScript pop-up box with two windows

Struggling to create two separate dialog boxes using this code. The issue is that when I add the code for the second dialog box, it only appears if the first one does too. Here's the code for the first dialog: function showPopUp(el) { var ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

The Node.js POST request is unexpectedly returning 'undefined'

I'm currently working on a project for an online course and I'm encountering an issue with making an API call. It seems that I am getting undefined responses to my post request because the user input is not being retrieved properly. Below are the ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

Having difficulty parsing or assigning JSON response: The response is being interpreted as [object Object]

Working with the Flickr API, Javascript/JQuery, and AJAX, I have the following code: function getRequest(arguments) { var requestinfo; $.ajax({ type: 'GET', url: flickrurl + '&'+ ...

Observing changes to attributes in AngularJS is a useful feature that allows for

I am looking to update the attribute of an element by using its id and have the element respond to this change. After trying to showcase my situation in a plunkr, I encountered issues with even getting ng-click to function properly. My goal is to invoke ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

Repeating the setTimeout function in a loop

I've been delving into JavaScript and trying to understand it better. What I'm aiming for is to have text displayed on the screen followed by a countdown sequence, like this: "Test" [1 second pause] "1" [1 second pause] "2" [1 second pause ...

Is there a way to efficiently line up and run several promises simultaneously while using just one callback function?

I am currently utilizing the http request library called got. This package makes handling asynchronous http connections fast and easy. However, I have encountered a challenge with got being a promisified package, which presents certain difficulties for me ...

When transmitting a variable from JavaScript to PHP using Ajax, the data appears to be missing

While attempting to pass a simple string variable using an onclick event, I encountered an issue where the request was successful but the response in the console displayed as empty. Additionally, the xvar variable did not come through properly resulting in ...

Utilize the Material UI feature to call the function

How can I pass a function as a prop to my Material UI component if the function is undefined within the component? import React, { Component } from 'react'; import styled from 'styled-components'; import InputBase from '@material- ...

Best practices for building an Ember frontend and Node backend application

I'm currently working on a project that involves an ember frontend and a node backend. Within my ember-cli app, I've configured the .ember-cli file to proxy requests to node like this: { "proxy": "http://localhost:3000" } I've had to es ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

Preventing the insertion of a line break when using Shift + Enter in Vuejs

Whenever I use a textarea to enter text, I find that I have to press Shift + Enter every time to send the text. However, upon sending, it adds /n at the end. I prefer using the Enter key for newline instead of submitting the form. Example: hello => ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

The IIS URL rewrite is causing issues with the rewriting of CSS and JS files

Struggling with my URL rewrites - every time I set up a rewrite for a page, it ends up affecting the CSS and JS files linked within the webpage, resulting in them not displaying properly. In an attempt to fix this issue, I tried using fully qualified path ...