Search code examples
javascriptjqueryhtmlonerror

How to handle source not exist in audio video html5?


How to handle source that not exist in audio video html5?

i tried https://www.w3schools.com/TAgs/av_event_error.asp: pure javascript

<audio controls onerror="alert(1);">
  <source src="http://somethingthatnotexist" type="audio/mpeg">
</audio>

with jquery

<audio controls ">
  <source src="http://somethingthatnotexist" type="audio/mpeg">
</audio>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
    $(function(){
        $('audio').on('error', function(){
            alert(1);
        })
    });
</script>

but not solved yet.

the correct way to do this is only place property src inside <video> tag not inside <source> tag. like this: works on both javascript and jquery

<audio id="myaudio" controls src="http://somethingthatnotexist"></audio>

But this looks akward for me, because:

  1. i need provide more than 1 audio to my client

  2. so many player plugins/library out there that use <audio><source src=""></source></audio> not <audio src=""></audio>

thanks for help.


Solution

  • Try this

    <audio controls>
      <source id="my_audio" src="http://somethingthatnotexist" type="audio/mpeg">
    </audio>
    

    and

    $("#my_audio").on("error", function (e) {
      alert("Error with source file!");
    });