Audio does not play through javaScript

I have an issue where audio does not play and I dont know why.

I have this audio tag and buttons in this .ejs document, because I am using nodejs and it goes like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title><%= title %></title>
</head>
<body>
    <audio id="audio">
        <source id="audioSource" src="" type="audio/mpeg"/>
        Your browser does not support the audio element.
    </audio>

    <button onclick="playAudio()" type="button">Play Audio</button>
    <button onclick="pauseAudio()" type="button">Pause Audio</button> 
    <button onclick="check()" type="button">Check Audio Status</button>

    <script src="/js/sum.js"></script> 
</body>
</html>

on the bottom there I connect a JavaScript document in the document there are a few functions for each button the play, pause and check status when the browser is booted up it should start playing one of the 4 mp3 files I have in my music folder after that, it listens for when the audio is done and then picks a random number 1-4, and sets the audio source the new sound.

document.getElementById("audio").addEventListener("ended", myFunction);
const audio = document.getElementById("audio");
const source = document.getElementById('audioSource');

let firstTime = 0;

function check(){
   if (audio.duration > 0 && !audio.paused) {
       alert("audio is playing");
   } else {
       alert("audio is not playing");
   }
}


function myFunction() {
   const i = Math.floor(Math.random() * 4) + 1;
   source.src = `/music/sound${i}.mp3`;
   audio.play();
}

function playAudio() { 
   if (firstTime == 0){
       firstTime += 1;
       let i = Math.floor(Math.random() * 4) + 1;
       source.src = `/music/sound${i}.mp3`;
       audio.play();
   } else {
       audio.play(); 
   }
} 
function pauseAudio() { 
   audio.pause(); 
} 

The issue is that, it doesnt play anything, and I dont know why, any help is appreciated

In theory it should go something like – browser launches, user clicks play, and it plays audio after audio, with the ability to pause.

Answer

Setting the audio source directly on the audio element should help. Here’s a quick example.

The HTML:

<audio id="audioSource" src=""></audio>

The JS:

const audioElement = document.getElementById("audioSource");
audioElement.src = `path/to/your.mp3`

You ought to add some kind of listener to ensure that the audio can play, as well (see MDN for details on this). Here’s an extended version of the previous example, which you could use to ensure that:

const audioElement = document.getElementById("audioSource");

function onCanPlay(e) {
  this.play();
}

audioElement.addEventListener("canplaythrough", onCanPlay);

audioElement.src = `path/to/your.mp3`

Note that it’s important to set the source after you attach your “can play” listener.