Scripting Media Elements

Contact Us or call 1-877-932-8228
Scripting Media Elements

Scripting Media Elements

The audio and video elements are accessible and controllable via the DOM. Here are some of the important methods and properties:

Method/Property Description
currentTime Read/Write. The current play location in seconds.
duration Read only. The length of the media file in seconds.
played Boolean. True if media file has been started.
ended Boolean. True if media file has been played in full.
autoplay Boolean. Read/Write.
loop Boolean. Read/Write.
play() plays media from current location (as per currentTime)
pause() pauses media

The following demo shows how to use the media API to create rudimentary custom controls and to report the current time of a media file.

Code Sample:

---- C O D E   O M I T T E D ----
	var playTimer;

	window.addEventListener("load",function() {
	function play() {
	function reportTime() {
		var curTime = document.getElementById("my-audio").currentTime;
		playTimer = setTimeout(reportTime,500);
	function pause() {
		if (typeof playTimer != "undefined") {
	function restart() {
<h1>HTML5 Audio - JavaScript</h1>
<article id="poem">
		<h2>Casey at the Bat</h2>
		<h3>By Ernest Lawrence Thayer</h3>
		<h4>from the San Francisco Examiner - June 3, 1888</h4>
	<audio id="my-audio">
		<source src="../Media/casey-at-the-bat.ogg" type="audio/ogg; codecs=vorbis">
		<source src="../Media/casey-at-the-bat.mp3" type="audio/mpeg">
	<menu type="toolbar">
		<button id="cmd-play" title="Play">Play</button>
		<button id="cmd-pause" title="Pause">Pause</button>
		<button id="cmd-restart" title="Restart">Restart</button>
	<div id="time-display">
		Time: <output id="play-time">0</output> seconds.
---- C O D E   O M I T T E D ----


  1. The menu with the three buttons.
  2. The output element to show the current time.
  3. The JavaScript:
    1. When the window loads, we add event listeners for each of the three menu buttons to call the play(), pause(), and restart() functions.
    2. play() - calls the audio element's play() method and then calls the reportTime() function.
    3. reportTime() - populates the output element with the audio element's currentTime value, rounded to the nearest second. Iteratively calls itself every half second to recheck the currentTime value.
    4. pause() - calls the audio element's pause() method and clears the timer.
    5. restart() - sets the audio element's currentTime value to 0 and calls play().