For continuing our HTML5 tutorial on audio element, we have started a series of practical examples to illustrate the events and attributes more efficiently. This post example is about seeking the played sound . . .
Before starting it is essential to have a view of the example. We want to make a new seeking bar for the audio element; so it must be updated by the audio element and, in reverse, it must have ability to set the element seeking bar value. To do this we have used ‘range‘ type of the ‘input‘ elements (refer to New HTML5 input types for the forms). The code is:
<audio id=”aud” src=”3.mp3″ controls
preload=”metadata” onloadedmetadata=”mDur()” ontimeupdate=”mPlay()”>
</audio><br>
<input id=”dur” type=”range” name=”rng” min=”0″ step=”0.25″ value=”0″ onchange=”mSet()”>
<script>
var aud= document.getElementById(‘aud’)
var dur= document.getElementById(‘dur’)
function mDur(){dur.max= aud.duration}
function mPlay(){dur.value=aud.currentTime}
function mSet(){aud.currentTime=dur.value}
</script>
You must see something similar to:
New events and attributes are bolded in the above example. First one audio element is made and two event handlers for ‘loadedmetadata‘ and ‘timeupdate‘ events are added to it. The first one is fired when the information of the file (metadata) is loaded completely, and the second one is fired when the playback position is changed, either manually or during the file playing.
Then the ‘range‘ element is made. Note that some browsers may not support this element and we have used Chrome here. This element has also a handler for when its value changes (‘onchange‘). Now it’s time to define the functions for handling the events. The ‘mDur()‘ function, which is called when the metadata is loaded, sets the ‘range‘ element maximum value to the file duration, found from ‘duration‘ attribute of the audio element. The ‘mPlay()‘ function sets the ‘range‘ element value to the current playing time; and the ‘mSet()‘ function do it reversely. The ‘currentTime‘ attribute is used for both getting and setting the current playing time value of the audio element (in the second unit).
More events and attributes of HTML5 audio element are discussed in the next examples . . .
