Skip to content
Advertisement

Audio player returns Uncaught (In promise): (DOMException) The element has no supported sources

So in my audio player (ka-musicplayer.glitch.me) i saw a flaw that when i played audio by typing the path to an MP3 it returned that. If i predefine the MP3s, it works. Feel free to see the code here.

   var input = document.getElementById("input");
      var inputVal = "";
      if (input) {
        inputVal = input.value;
      }

      var player = new Audio(inputVal);
      player.crossOrigin = "anonymous";
  var s2 = document.createElement("button");
      s2.innerText = "Play";
      s2.addEventListener("click", function() {
        player.src = inputVal;
        player.play();
      });
      document.body.appendChild(s2);
<!DOCTYPE html>
<head></head>
<body>


<input id="input" />
Check JS Console in current browser for error

Advertisement

Answer

After investigating the Audio() constructor, I’ve revised your code.

Firstly, you could write the button element in your HTML and add an event listener rather than generating it dynamically.

<!DOCTYPE html>
<head></head>
<html>
<body>
    <input id="input" type="text">
    <button id="play">Play</button>
</body>
</html>

Also, at least in the snippet you provided, you’re grabbing the value of the input right away. I’d grab the value when you click the play button:

const input = document.getElementById("input");
const playButton = document.getElementById("play");


playButton.addEventListener("click", function() {
    if (input.value.length) {
        let inputVal = input.value;
        var player = new Audio(inputVal);
        player.crossOrigin = "anonymous";
        player.addEventListener("canplaythrough", function() {
            player.play();
        })
    }
})

Notice the "canplaythrough" listener on the player–this delays playing the audio until the audio element and file itself have been completely loaded. You also didn’t need to assign a src to the element; the URL passed into the Audio() constructor is automatically assigned to the source.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement