HTML 5 <audio> - Play file at certain time point

Viewed 58308

I have a simple auto playing snippet that plays the audio file however I was wondering either in JavaScript or as an attribute play that file at a certain time (ex. 3:26).

<script type="text/javascript">
    var myAudio=document.getElementById('audio2')
    myAudio.oncanplaythrough=function(){this.play();}
</script>

<audio id="audio2" 
       preload="auto" 
       src="file.mp3" 
       oncanplaythrough="this.play();">
</audio>

Any help would be great. Thanks in advance :)

3 Answers

The best way to do this is to use the Media Fragment URI specification. Using your example, suppose you want to load the audio starting at 3:26 in.

<audio id="audio2" 
       preload="auto" 
       src="file.mp3#t=00:03:26" 
       oncanplaythrough="this.play();">
</audio>

Alternatively, we could just use the number of seconds, like file.mp3#t=206.

You can also set an end time by separating the start from the end times with a comma. file.mp3#t=206,300.5

This method is better than the JavaScript method, as you're hinting to the browser that you only want to load from a certain timestamp. Depending on the file format and server support for ranged requests, it's possible for the browser to download only the data required for playback.

See also:

I have a simple answer that will work for all

1- create a button that when clicked it plays the audio/video
2- test that audio playing when you click the button if it works to hide the button and
3- click button when page loads

    window.onload =function(){
        document.getElementById("btn").click();
    }
Related