Are you willing to learn how <audio> tag works, if yes then you have to understand the following aspects of the HTML <audio> tag:
- The basic syntax of <audio> tag
- Attributes of <audio> tag
- Commonly used audio formats
- Browser’s support for <audio> tag
- How to use <audio> tag
Let’s get started!
Syntax
The bellow-given snippet shows the basic syntax of the <audio> tag:
- src and type are attributes of <audio> tag, we will learn about them in the attributes section.
- Here, a key point to understand is anything we write in inside the starting <audio> and ending </audio> tags will be displayed only if the browser doesn’t support the audio file
Attributes
There are some attributes that can be used in the <audio> tag as listed below:
- controls: as the name itself suggests, it enable us to control the audio file i.e. it specifies what controls should be visible to the user e.g. play, pause, mute, etc.
- src: determines the address of the audio file.
- loop: it enables the looping structure i.e. audio files will be played over and over again.
- muted: it determines whether the audio file will be muted
- preload: it determines the author’s view about how audio file will be loaded when the webpage loads
- autoplay: it determines the file will be played instantly
Formats
<audio> tag is a modern tag introduced in HTML5, currently, it supports three file formats i.e. “mp3”, “wav”, “ogg”.
Browser Support
Following is the list of browsers for the various audio file formats:
- Chrome, Microsoft Edge, Opera, and Mozilla Firefox support all three formats i.e. mp3, wav, ogg.
- Internet Explorer supports only mp3 format
- Safari supports wav and mp3 formats
How to use <audio> tag
Consider the below-given code snippet to understand how to use the <audio> tag to embed an audio file to a webpage:
This code performs the following functionalities:
- We Added “controls” attribute in the <audio> tag so that a user can control the file in terms of play/pause, mute/unmute etc.
- <source> tag help us in specifying the multiple files.
Following will be the output for the above code snippet:
Multiple file formats can be specified in the <audio> tag in such case the browser will play the first recognized source.
Let’s modify the example a little bit and add the “muted” attribute in the <audio> tag
Now when we run the code, initially the file will be muted:
Similarly, you can use the autoplay, loop, or any other attribute according to your need.
Conclusion
Audio tag can be used to add an audio file to any document/website, different attributes can be used within the audio tag to perform different functionalities. If we specify the addresses of more than one audio file then the browser will attach the first file to the document. This article demonstrates what is HTML <audio> tag and how to use <audio> tag. Moreover, it provides a detailed explanation of the available audio file formats and supported browsers.