Search code examples
javascripthtmlaudiohtml5-audio

Cross-browser HTML5 audio player


I am using audio tag to play a wav audio, My url is genereted by URL.createObjectURL() and the url is like blob:http://localhost/9fa2ef06-ade6-4027-89f8-06cd2c176405

As the url has no extension, I have some issue with safari

The following code is works on chrome and not works on safari(Audio player is disabled)

<audio src="MY_BLOB_URL" type="audio/wav">
</audio>

The following code is works on safari and not works on chrome

<audio controls>
  <source src="MY_BLOB_URL" type="audio/wav">
</audio>

I tried weird codes like the following and cannot find any way to works on both browsers

<audio src="MY_BLOB_URL" type="audio/wav">
  <source src="MY_BLOB_URL" type="audio/wav">
</audio>

What's wrong here? And how can I have a cross-browser HTML5 audio player with single code?


Solution

  • I've tested the following code on Windows PC using Chrome, Edge & Firefox.
    Let's hope it also works on Safari.

    PS: For future readers, this code would also work with an MP3 blob (set as accept=".mp3").

    <!DOCTYPE html>
    <html><head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> </head>
    
    <body>
    
    <div style="z-index: 1; overflow:hidden; position: absolute; top: 100px; left: 50px">
    <audio id="tag_Audio1" controls>
    <source type="audio/wav">
    </audio>
    </div>
    
    <br><br><br><br>
    
    <div style="z-index: 1; overflow:hidden; position: absolute; top: 10px; left: 50px">
    <p> Choose an WAV file...</p>
    <input type="file" id="choose_media" accept=".wav" />
    </div>
    
    <script>
    
    var file; var reader;
    var tmpElement; //# is reference to aTag for holding image content.
    var file_Blob; //# is reference to file BLOB (data of selected file).
    
    const  myAudio = document.getElementById("tag_Audio1");
    document.getElementById("choose_media").addEventListener("change", onFile_Selected, false);
    
    function onFile_Selected(evt) 
    {
        file = evt.target.files[0]; //# access to selected file
        
        reader = new FileReader();
        reader.readAsDataURL(file); //# load selected file as Blob
        reader.addEventListener("loadend", onFile_Loaded, false);
    }
    
    function onFile_Loaded(evt) 
    {
        if (evt.target.readyState == FileReader.DONE) 
        {
            //# remove any current SRC
            myAudio.removeAttribute("src");
            
            //# create blob
            file_Blob = (window.URL || window.webkitURL).createObjectURL(file);
            
            //# apply blob & test play
            myAudio.setAttribute("src", file_Blob);
            myAudio.load();
            myAudio.play();
        }   
    }
    
    </script>
    
    </body>
    </html>