Search code examples
javascripthtmlaudio

Playing audio which source path contains "%" in javascript


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.


Solution

  • 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.