Home > Software design >  Reactjs can't play audio file with "#" in the SRC URL
Reactjs can't play audio file with "#" in the SRC URL

Time:09-23

I am building a normal app that have 2 button, each will play 1 WAV audio file when clicked.

Here's the code :

import React from "react";
function Test() {
  const play = (note) => {
    new Audio(document.getElementById(note).src).play();
  };
  return (
    <>
      <div>TEST</div>
      <button onClick={() => play("C5")}>Play C5</button>
      <button onClick={() => play("C#5")}>Play C5 sharps</button>
      <audio id="C5" src="./audio/C5.wav" />
      <audio id="C#5" src="./audio/C#5.wav" />
    </>
  );
}

export default Test;

The C5 file play normal. But React can't seem to play the C#5 file and I get this error:

index.js:1 Uncaught Error: The error you provided does not contain a stack trace.
    at L (index.js:1)
    at Y (index.js:1)
    at index.js:1
    at index.js:1
    at l (index.js:1)
L @ index.js:1
Y @ index.js:1
(anonymous) @ index.js:1
(anonymous) @ index.js:1
l @ index.js:1
localhost/:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.

Is it because of the # in the file path ? How can I fix this without changing the file name ?

All the audio files are put in public folder if that help. Please help me in this. Thank a lot.

CodePudding user response:

The hash sign ('#') denotes the start of a fragment identifier in the URL. Neither the hash mark nor characters following it are sent the server when making an HTTP request.

You could try percent encoding the hash-used-as-sharp sign in the url as

 src="./audio/C#.wav"

Altnernatively rename the file to not use special characters, e.g. csharp.wav

CodePudding user response:

Try replacing # with # as it is the HTML escape sequence for #.

Normally in a URL, a hash mark ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. So you need to escape it using #.

You can do it like this:

<audio id="C5" src={"./audio/C#5.wav".replace('#', '#')} />

Or if you want to call just this one file:

<audio id="C5" src="./audio/C#5.wav" />
  • Related