HTML and CSS Reference
In-Depth Information
loop
Another self-descriptive attribute,
loop
tells the browser to loop the audio when
playing forward.
This is less offensive than the
autoplay
attribute, but it should still
be used with discretion.
Like
controls
, both
autoplay
and
loop
are Boolean attributes, so you simply include
them in the opening
audio
tag when you want them:
<audio controls
loop
>
Discussion
What if you want more control than these basic attributes provide? Fortunately,
audio
and
video
have attributes, events, and methods you can manipulate with
JavaScript to create custom controls, including:
canplaytype(
type
)
Returns a string indicating whether the browser can play a particular type of media
currentTime
Indicates the current playback position, denoted in seconds
duration
Gives the length of the audio file in seconds
play();
Starts playback at the current position
pause();
Pauses playback if the audio is actively playing
For example, suppose you want to include controls that allow the user to jump to a
specific time in the audio file. You can add this functionality with a
button
and a dash
of JavaScript to manipulate the
play()
method based on the read/write property
currentTime
:
<audio>
<source src="audio.ogg">
<source src="audio.mp3">
</audio>
<button title="Play at 30 seconds"
onclick="playAt(30);"
>30 seconds</button>
<script>
function playAt(seconds){
var audio = document.getElementsByTagName("audio")[0];
audio.currentTime = seconds;
audio.play();
}
</script>
