Search code examples
javascriptnode.jshtml5-audio

How can I correctly format file reference for HTML5 Audio element?


I'm using the HTML5 <audio> element in a Node.js app and I'm running in to problems with the file references and special characters when setting the src.track. When referencing the file location from my mySQLite3 database, I'll send a location formatted as:

/Users/admin/Music/iTunes/iTunes Music/Nelly/Nellyville/13 #1.mp3

I get the following error:

GET file:///Users/admin/Music/iTunes/iTunes%20Music/Nelly/Nellyville/13%20 net::ERR_FILE_NOT_FOUND

It is obviously erroring out on the "#" in this particular string and ignoring the remainder of the string. This formatting works for all references except for those with special characters. I've tried every type of encoding, escaping, and formatting I can think of including encodeURIComponent() and encodeURI().

I can output a string in javascript using encodeURIComponent() which produces a working link that I can paste in my browser to correctly reference the file. However, if I set my track.src using the output from encodeURIComponent(), it adds my project directory on to the string and errors out as so:

GET file:///Users/admin/Code/project/src/%2FUsers%2Fadmin%2FMusic%2FiTunes%2FiTunes%20Music%2FNelly%2FNellyville%2F13%20%231.mp3 net::ERR_FAILED

Solution

  • Okay, after probably 100 different variations of src input in to the <audio> element, I determined that, at least in my Electron app, it uses some sort of hybrid between encodeURI and encodeURIComponent. encodeURIComponent encodes the "/" which will not work, but encodeURI does not encode the characters which were causing the problem, such as "#". So, here is the way I've figured out how to make this work:

    function URLFormat(input){
        let URIencodedURL = encodeURIComponent(input);
        let EncodedURL = 'file:///' + URIencodedURL.replaceAll("%2F","/");
        return EncodedURL;
    }
    

    This provides me with a proper input path for the <audio> element even in the case of files with special characters.