简体   繁体   中英

How to know when a HTMLMediaElement has finished

In javascript I'm playing a sound like this:

var mySound = new Audio('/my-url');
mySound.play();

Is there a way to know when it has finished to play ? I've seen a ended property but I'm more looking for an event, a Promise, or something like that.

Thanks

By using HTMLMediaElement like below you can use fined whether media is finished playing or not

var obj = document.createElement('video');
console.log(obj.ended);

Here HTMLMediaElement.ended returns Boolean value stating whether media is finished(TRUE) or not(FALSE).

But, you want another way of handling such event. Thus you can use jquery event like below:

 <script>
  $(document).ready(function(){
    $('video').on('ended',function(){
      console.log('Video has ended!');
    });
  });
</script>

And without jquery:

<script>
  document.getElementById('video').addEventListener('ended',function(){
    console.log('Video has ended!');
  }, false);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM