Search code examples
javascripthtml5-videohtml5-audio

Is there a way to trigger an event when an audio or video control reaches a specified stopping point?


I have an HTML audio element implemented like this:

<audio id="urlMedia" controls="controls" autoplay="autoplay" src="/ma/some.flac#t=0,30"></audio>

The file is much longer than 30 seconds. Without the ",30" termination on the src url it would normally play to the end of the file and then trigger an "ended" event which allows me to update the src url via Javascript. I am capturing the event with something like this:

var media = document.getElementById("urlMedia");
    media.addEventListener("ended", function() {
      alert("end reached");
      }
    }, true);

I want to be able to do this in the case when the control stops at a designated point such as 30 seconds into play as I in the example here. Is this possible. The control does not seem to trigger any kind of event when it reaches the end of 30 seconds. I just stops playing.

I am not looking for a JQuery or other large package solution here - but a Javascript solution.

Thanks.


Solution

  • You could use the timeupdate event:

    const audio = document.getElementById('urlMedia');
    
    audioElement.ontimeupdate = function() {
    
        if ( audioElement.currentTime > 30 ) {
        
          // Do something here
        
        }
        
    }
    <audio id="urlMedia" controls="controls" autoplay="autoplay" 
      src="/ma/some.flac#t=0,30"></audio>

    Documentation on MDN for timeupdate