The <audio>
tag in HTML is used to embed audio content, such as music or sound effects, directly into a web page. It provides a way to include audio files that can be played by the user’s browser. The <audio>
tag supports various audio formats, and you can specify multiple source files to ensure compatibility with different browsers.
Syntax
<audio controls>
<source src="audiofile.mp3" type="audio/mp3">
Your browser does not support the audio element
</audio>
Attributes
Attributes | Description |
---|---|
controls (optional) | Adds audio controls, such as play, pause, and volume, to the audio player. |
src (required) | Specifies the URL of the audio file. |
type (optional) | Specifies the MIME type of the audio file. This helps the browser understand the format of the audio. |
Example 1: Basic usage of <audio>
Tag
<!DOCTYPE html> <html lang="en"> <head> <title>HTML audio Tag</title> </head> <body> <h2>Background Music</h2> <audio controls> <source src="background-music.mp3" type="audio/mp3"> Your browser does not support the audio element </audio> </body> </html>
In this example, the <audio>
tag is used to embed background music with audio controls.
Example 2: Multiple Sources for Browser Compatibility
<!DOCTYPE html> <html lang="en"> <head> <title>HTML audio Tag</title> </head> <body> <h2>Sound Effects</h2> <audio controls> <source src="sound-effects.ogg" type="audio/ogg"> <source src="sound-effects.mp3" type="audio/mp3"> Your browser does not support the audio element. </audio> </body> </html>
This example includes multiple <source>
elements to provide different audio formats for better browser compatibility.
Browsers Compatibility
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
3 | 12 | 3.5 | 10.5 | 3.1 |