Search code examples
htmlhtml5-audio

HTML Auto-Play a song and StartAt


I have this code, but I do not know how to make the song start from 0:19 seconds. Could you help me out?

<div class="fin-subheading">
  &middot; ROLEPLAY &middot;
  <audio id='music' volume='0.5' autoplay controls>
    <source src="anonymous.mp3" type="audio/mpeg">
  </audio>
</div>

<script>
  var audio = document.getElementById("music");
  audio.volume = 0.3;
</script>

Solution

  • You can specify a playback range in the src attribute itself. See the docs here:

    When specifying the URI of media for an or element, you can optionally include additional information to specify the portion of the media to play. To do this, append a hash mark ("#") followed by the media fragment description.

    A time range is specified using the syntax:

    #t=[starttime][,endtime]

    So instead of:

    <source src="anonymous.mp3" type="audio/mpeg">
    

    simply put:

    <source src="anonymous.mp3#t=n,m" type="audio/mpeg">
    

    where n and m are the start and end times, respectively.

    The range can also be unbounded as well. So you could, for instance do this:

    <source src="anonymous.mp3#t=19" type="audio/mpeg">
    

    which will start at 19 seconds and play through till the end; or even this:

    <source src="anonymous.mp3#t=,19" type="audio/mpeg">
    

    which will start from the beginning through 19 seconds.