With HTML5, we are provided numerous tools and tags to work with multimedia. One of the new things that come with HTML5 is the ability to embed audio and video without needing plugins like Flash.
In this article, we’ll look at how to add audio and video elements to a web page and control it with JavaScript.
Adding Audio or Video Elements
To add audio and video elements, we use the audio
and video
tags respectively. They have a few attributes. They are:
autoplay
— specifies whether the audio or video will play automaticallycontrols
— specifies whether playback controls are shownloop
— specifies whether we want to play the clip again once it endsmuted
— specifies if sound should play or notpreload
— specifies which part of the clip should be preloaded. It can beauto
, which loads everything,metadata
, which loads only the metadata, ornone
, which loads nothingsrc
— the URL for the clip
To embed audio in our web pages, we can write the following:
<audio controls>
<source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_OOG_1MG.ogg" type="audio/ogg">
<source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
In the code above, we specified the audio in different formats of the audio that we want to load.
Likewise, we can do the same with video:
<video controls width="250">
<source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
In both pieces of code, then text within the tag is the fallback text in case the browser doesn’t support these tags.
Controlling the Elements with JavaScript
We can customize the functionality of the audio or video element with JavaScript code. The following are methods are available for controlling the playback of audio or video elements:
play
— start playing the audio or videopause
— pausing the audio or videoload
— reload the audio or video elementaddTextTrack
— add a text track to audio or videocanPlayType
— check if the browser can play the specified type of audio or video
There’re also some properties that we can set the control the audio or video playback:
currentTime
— sets the current time of the audio or video in secondsdefaultMuted
— indicate whether the audio output should be muted by defaultdefaultPlaybackRate
— a number indicating the default playback for the medialoop
— boolean indicating whether we want restart playback after it endsmuted
— boolean we can set for muting the audioplaybackRate
— sets the playback rate of the clipvolume
— change the volume of the audio or video
We can use these methods and value properties as follows. First, we add our clip into our HTML code:
<video controls width="250">
<source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">
Sorry, your browser doesn't support embedded videos.
</video>
Then we can add buttons to change various things like the playback rate or muting the audio as follows. First, we add some buttons to let us click to change the settings:
<button id='fast-button'>1.5x speed</button>
<button id='fastest-button'>2x speed</button>
<button id='mute'>Toggle Mute </button>
Then we add some code to get the button and video elements and set the settings accordingly.
const fastButton = document.querySelector('#fast-button');
const fastestButton = document.querySelector('#fastest-button');
const muteButton = document.querySelector('#mute');
const video = document.querySelector('video');
fastButton.onclick = () => {
video.playbackRate = 1.5
}
fastestButton.onclick = () => {
video.playbackRate = 2
}
muteButton.onclick = () => {
video.muted = !video.muted;
}
In the code above, we get the elements and then in the click event handlers for the buttons, we set the playbackRate
and toggle the muted
properties for the video.
We can do something similar with the methods. For example, we can add the following buttons:
<button id='play'>Play</button>
<button id='pause'>Pause</button>
Then we can add the following buttons click handlers to play and pause the clip programmatically:
playButton.onclick = () => {
video.play();
}
pauseButton.onclick = () => {
video.pause();
}
This is handy for creating custom video and audio players that don’t use the default browser style, along with the controls
attribute for showing or hiding the controls.
Another example is making a seek bar for our clip. We can do that by adding a range slider as follows:
<input type="range" name="time" id='time' min='0'>
Then we can set the max
attribute of the slider to the duration of our clip and add an onchange
event handler as follows:
timeInput.max = video.duration
timeInput.onchange = (e) => {
video.currentTime = e.target.value;
}
The let us seek to anywhere from the start to the end of the video as we slide back and forth with the slider.
Events
Audio and video elements also have the following events fired, so we can handle them with event handlers we wish to:
canplay
— the browser can play the media, but estimates that not enough data will be available to finish playback without stopping to buffer.canplaythrough
— browser estimates that playback finish without stopping for more bufferingcomplete
— playback endsdurationchange
— duration has been updatedemptied
— media has become emptyended
— playback ended before the end of the clip was reachedloadeddata
— the first frame has finished loadingloadedmetadata
— metadata has been loadedpause
— playback is pausedplay
— playback beganplaying
— playback is ready to start after having been paused or delayed due to lack of dataprogress
— fired periodically as browser loads a resourceratechange
— playback rate changedseeked
—seek operation completedseeking
— seek operation beganstalled
—a user-agent tries to fetch media data, but nothing is coming insuspend
— media data loading has been suspendedtimeupdate
— the time indicated by thecurrentTime
attribute has been updatedvolumechange
— volume changedwaiting
— playback stopped because of a temporary lack of data