Home » Jquery » javascript – How to check if external mp3 exists by catching the audio player behavior-Exceptionshub

javascript – How to check if external mp3 exists by catching the audio player behavior-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

When I embed and external mp3 file in my own website, if the target file was removed from the target server, the html5 player will be grayed out and the controls are disabled. How can I catch this event and show the availabilty of mp3 in other ways like a green or red check mark. As the file availabilty STATUS is visible on the browser I think there should be an event or a way to catch the final status. How can I can catch the availabilty status?

This is a sample code I am looking for but by replacing the STATUS CHANGE and STATUS:

<audio controls id="mymp3">
  <source src="http://example.com/1.mp3" type="audio/mpeg">
</audio>
$("#mymp3").on("STATUS CHANGE", function() {
 if (STATUS) { 
   $("#checkmark").attr("src","green.png");
 } else {
   $("#checkmark").attr("src","red.png");
 }
})
How to&Answer:

You can check the existence of file using jQuery and head method.

$.ajax({
    url:'http://site/somefile.mp3',
    type:'HEAD',
    error: function() {
        // not exists
    },
    success: function() {
        // exists
    }
});