In this article, we'll learn which tag we use to create a sound element in HTML, as well as the attributes that define how the audio will behave.
Getting straight to the point, to add sounds to an HTML document, you need to use the <audio>
tag. First, we create the <audio>
tag and then add the controls attribute to display a playback control.
<audio controls>
</audio>
Next, we add the <source>
tag with the path to the audio file.
An interesting detail: we can also add more than one file with a different extension as a safety measure, HTML will consider the first supported file.
In this case, we'll add a file with the .wav
extension. If the file isn't supported or has a problem, HTML will consider the next supported file.
Finally, if none of the files are supported in the browser, we can display a text message informing the user of the error.
<audio controls>
<source src="./audio/sound-effect.wav" type="audio/wav" />
<source src="./audio/sound-effect.mp3" type="audio/mp3" />
Your browser does not support the audio tag.
</audio>
The audio files supported by the browser are:
- MP3
- WAV
- OGG
We also use the type
attribute in the <source>
tag to inform the browser of the file type being used, it's a good way to maintain semantic HTML.
This will be the result:
Audio Tag Attributes
In addition to the controls
attribute, we can include other attributes in the <audio>
tag, most of which do not need to be assigned a value.
-
muted
specifies that the audio is muted -
loop
specifies that the audio plays in a loop -
autoplay
specifies that the audio plays automatically
<audio controls autoplay loop>
<source src="./audio/sound-effect.wav" type="audio/wav" />
<source src="./audio/sound-effect.mp3" type="audio/mp3" />
Your browser does not support the audio tag.
</audio>
In the case of the code above, as soon as the page loads, the audio will play automatically due to the autoplay
attribute and will continue playing due to the loop
attribute.
This article covered
-
<audio>
Tag -
<source>
Tag -
<audio>
Tag Attributes
Author
Daniel Nogueira
LinkedIn
Top comments (0)