HTML and CSS Reference
In-Depth Information
Listing 8-1.
The initial script element
<script type="text/javascript">
var audio = document.getElementById("audio");
function setupSeek() {
var seek = document.getElementById("audioSeek");
seek.min = 0;
seek.max = audio.duration;
seek.value = 0;
var duration = document.getElementById("duration");
duration.innerHTML = "0/" + Math.round(audio.duration);
}
function togglePlay() {
if (audio.paused || audio.ended) {
audio.play();
}
else {
audio.pause();
}
}
function updatePlayPause() {
var play=document.getElementById("play");
if (audio.paused || audio.ended) {
play.value="Play";
}
else {
play.value="Pause";
}
}
function endAudio() {
document.getElementById("play").value = "Play";
document.getElementById("audioSeek").value = 0;
document.getElementById("duration").innerHTML = "0/" + Math.round(audio.duration);
}
</script>
This code first declares the
audio
variable that references the
audio
element. Since this is used by most of
the functions, it's more efficient to get it once and store it in a variable that all functions can access.
The first method,
setupSeek()
is called in response to the
ondurationchange
event. When the page is first
loaded, it doesn't know how long the audio clip is until the file is opened and the metadata is loaded. As soon
as the metadata has been loaded, the duration can be determined and the event is raised. The
setupSeek()
function uses the
duration
property to set the
max
attribute of the
audioSeek
range control. It is also used to
set the initial value of the
span
element. The
duration
property is expressed in seconds. Notice that the
Math.round()
function is called to round this value to the nearest integer.
The
togglePlay()
method is called when the user clicks on the Play button. If the current state of the
audio element is paused or ended, it calls the
play()
function. Otherwise it calls the
pause()
method. The
updatePlayPause()
method sets the label of the play button. If the audio is currently playing, the text is changed
to “Pause” since that will be the result if the button is clicked. Otherwise, the text is set to “Play”.