Sunday, 13 February 2011

How to reset/restart the position of a HTML5 audio clip

A simple google search didn't turn up with any direct results so this might be what you're looking for:

HTML:

<audio src="samples/brutaldeathmetal.mp3" id="audio" controls>


JavaScript:

var aud = document.getElementById('audio');
aud.addEventListener("ended", function(){
    this.currentTime = 0;
    this.pause();
});

What this does is it sets the playtime back to zero seconds when the audio clip ends.

Among the many javascript functions and properties of this tag you can use .play(), .pause(), .ended, .paused, and .duration to manipulate it. And you can even set the .currentTime property to a number within the range of your clip's playback duration (in seconds) to start midway through the clip if you wanted.

5 comments:

  1. Great. It just works!

    ReplyDelete
  2. don't work for me my song just stop where i said it to but it don't reset so i can replay it from the begining

    ReplyDelete
    Replies
    1. So you can definitely change the durationTime to any valid number? Then you should be able to set it to 0 and then immediately pause it using the .pause() method to keep it from playing back again.

      Delete