HTML and CSS Reference
In-Depth Information
Ti
■
The
togglePlay()
function responds to the play button being clicked and the
updatePlayPause()
function
responds to the
audio
element being started or paused. When the button is clicked, the
togglePlay()
method will
change the state of the
audio
element. This state change will raise either an
onplay
or
onpause
event, which are
both handled by the
updatePlayPause()
function. This is done this way because it is possible that the audio can be
played or paused through means other than clicking the play button. For example, if you left the
controls
attribute,
you would have both the native controls as well as the custom controls. Responding to the
onplay
and
onpause
events ensure the button label is always correct regardless of how the
audio
element is manipulated.
Finally, the
endAudio()
function is called when the audio has finished playing. This performs some
synchronization including setting the button label, and initializing the
range
and
span
controls.
Supporting Progress and Seek
Next, add the functions shown in Listing 8-2 to the same
script
element.
Listing 8-2.
Functions to support the range control
function seekAudio() {
var seek = document.getElementById("audioSeek");
audio.currentTime = seek.value;
}
function updateSeek() {
var seek = document.getElementById("audioSeek");
seek.value = audio.currentTime;
var duration = document.getElementById("duration");
duration.innerHTML = Math.round(audio.currentTime) + "/" + Math.round(audio.duration);
}
Just like with the play button, there is one event handler,
seekAudio()
, that responds to the input element
and a separate event handler,
updateSeek()
, that responds to the
audio
element. The
seekAudio()
function is
called when the user moves the slider on the range control. It simply sets the
currentTime
property using the
value selected by the range control.
The
updateSeek()
function is called when the
ontimeupdate
event is raised by the
audio
element. This
updates the range control to reflect the current position within the file. It also updates the span control to show
the actual position (in seconds). Again, the
currentTime
property is rounded to the nearest integer.
Controlling the Volume
The last set of functions is used to support both the volume control and the mute button. Add the code shown in
Listing 8-3 to the same
script
element that you have been using.
Listing 8-3.
Controlling the volume
function toggleMute() {
audio.muted = !audio.muted;
}