Audio and video can help to add interactive content to your website. Good part is that HTML5 offers easy way to embed audio and video files. It has a default player and most modern browsers support HTML player. In this article, we will explain how to embed audio and video files using HTML5.
Listen to Your Audio
The <audio> element in HTML5 is used to embed audio files to your webpage. Below is an example of how to embed audio on your site:
<!DOCTYPE html> <HTML> <HEAD> <TITLE>This is my audio</TITLE> </HEAD> <BODY> <AUDIO controls autoplay loop> <source src="my-audio.mp3"> <source src="my-audio.ogg"> </AUDIO> </BODY> </HTML>
- In order to ensure support in all web browsers it is good idea to use same audio file with .mp3 and .ogg formats using “source” attribute.
- The “controls” attribute displays the audio player control.
- The “autoplay” attribute starts automatically playing the music when the player is loaded.
- The “loop” attribute is used to loop the audio file continuously.
The audio player will look like below on Google Chrome browser:
It is not recommended to use “autoplay” attribute unless you needed, otherwise automatically playing the audio may disturb the user experience. It is better to provide the control to users.
View Your Video Too…
HTML5 also allows you to embed video on your page using <video> element. Similar to audio, video element also has attributes to control the display of the player on the browser. If the browser does not support the HTML5 video element then the text message present between the <video>…</video> tags will be shown on the browser. So it is a good practice to add some useful text within video tags.
Use the below code to insert a video player on your page:
<!DOCTYPE html> <HTML> <HEAD> <TITLE>This is my video</TITLE> </HEAD> <BODY> <VIDEO src=”my-video.mp4” poster=”thumbnail.png” width=”500” height=”400” preload controls loop> <P> This browser does not support HTML5 video </P> </VIDEO> </BODY> </HTML>
- “Controls”, “autoplay” and “loop” attributes offer similar function like audio element.
- “Preload” allows the browser to load the video when the page is loaded. It can take one of the three allowed values:
- “None” – no action needed by the browser till user plays the video.
- “Auto” – browser will preload the video
- “Metadata” – browser only collects the metadata information like duration of the video, size, etc.
- “Poster” attribute shows a thumbnail image till the time the video is loaded or the user clicks on the play button.