Using HTML5 Video and Audio Tags

Using HTML5 Video and Audio Tags

It is important to make websites more attractive and interactive to users. One of the ways to do that is to add video and audio files. HTML5 introduced a lot of cool new features and tags, and some of the new tags are <audio> and <video> tags.

How to Use Video and Audio Tags

The <audio> and <video> tags have very similar formatting:

<audio src="myfile.mp3" />
<audio src="myfile.mp3"></audio>

<video src="myfile.mp4" />
<video src="myfile.mp4"></video>

The tags are self-closing, so both formats would be considered correct. It’s really easy, isn’t it? The new tags themselves are not so complicated. However, video codecs are complex and create a lot of issues. Long story short, each browsers support different codecs, and because of this, it would be wise to add different video formats for maximum compatibility between browsers. The formats would then change to these:

<audio controls>
<source src="myfile.mp3" type="video/mp3" />
<source src="myfile.ogg" type="video/ogg" />
</audio>

<video controls>
<source src="myfile.mp4" type="video/mp4" />
<source src="myfile.webm" type="video/webm" />
<source src="myfile.ogv" type="video/ogg" />
</video>

In addition to these attributes, you could set width and height on the <audio> and <video> tags.

New Attributes for Video and Audio Tags

There are some new attributes that could be used on <audio> and <video> tags. I will list some below, and these attributes could be used for both audio and video:

  • preload – This attribute controls when the video or audio file will download. It is especially useful for large files.
  • loop – Using this attribute will make the audio or video file start over when it ends. It is a Boolean attribute, so all you need to do is include the word loop in the <audio> or <video> tag.
  • autoplay – Also a Boolean attribute, this attribute determines whether the video will start on page load or not.
  • controls – This is a Boolean attribute that enables users to pause or play the files without right-clicking on the video to start it. Because of this, it is a good practice to include this attribute. When this attribute is used, each browser will apply its own styled controls to the video or audio files. To have your own controls, you could make them through JavaScript.

Helpful Tools

There are many helpful tools out there to get started with HTML5 videos and audios. One of them is MediaElement.js. Another is Video.js. Both use JavaScript to help the video and audio files look uniform in different browsers and offer Flash fallbacks for browsers that are not compatible with these new HTML5 tags.

Conclusion

It is important to include video and audio files in your website. I hope this article was helpful in getting you started with HTML5 audio and video tags. If you would like to learn more about getting started with HTML5 in general, check out this article: Getting started with HTML5

By: Blueprint