skip to Main Content

So I have an audio file which name contains "%". So as far, I have the following tag <audio src="test%320.mp3" controls></audio>. However, I got an error while trying playing it, as if the file does not exist. Could anyone help me ?

I found some other thread where they used encodeURIComponent but I don’t know how that work and tried it anyway. But that still won’t work.

2

Answers


  1. You are right with encodeURIComponent, use it like that:

    const fileName = "test%320.mp3";
    const encodedFileName = encodeURIComponent(fileName);
    document.getElementById("audioID").setAttribute("src", encodedFileName);
    <audio id="audioID" controls></audio>

    The % will be url-encoded as %25 and the file should play with the corrected name.

    Login or Signup to reply.
  2. The % is a special character

    That is what is confusing Javascript. It is reading the %32 as the ASCII code hex 32, which is decimal 50, i.e. the character "2". Therefore Javascript is looking for a file called "test20.mp3".

    If you want to encode that, try using this to replace the string "test%320.mp3":

    encodeURI("test%320.mp3")
    

    That gives the result test%25320.mp3 which, when you send to Javascript, will be correctly interpreted:

    • %25 will be interpreted as %
    • 320 will be interpreted as 320

    So it will try to read file test%320.mp3.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search