Dremendo Tag Line

Embed Audio in HTML

Audio and Video

In this lesson, we will learn how to embed audio in an HTML document using the audio tag.

What is audio Tag in HTML

The <audio> tag is the most common and widely used way to embed audio in an HTML document. It is simple to use and supported by all modern browsers. The <audio> tag can be used to play audio files in various formats like MP3, WAV, and OGG.

video-poster

Supported Audio Formats and its Media Types

The table below shows the audio formats and their media types supported in HTML.

Audio Format Media Type
mp3 audio/mpeg
wav audio/wav
ogg audio/ogg

Attributes of the Audio Tag

  • src: This attribute specifies the URL of the audio file.
  • controls: This attribute adds the playback controls to the audio player.
  • autoplay: This attribute automatically plays the audio file when the page loads.
  • muted: This attribute mute the speakers when you play the audio.
  • loop: This attribute sets the audio file to play continuously.
  • preload: This attribute specifies whether the audio file should be loaded when the page loads.

How to Use <audio> Tag in HTML

Here is an example of how to use the <audio> tag to embed an audio file in an HTML document.

Example

<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<title>Audio Tag Example</title>
</head>

<body>
	<audio controls autoplay loop>
        <source src="audio-file.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</body>

</html>

In the above example, we used the audio tag with the attributes controls, autoplay and loop. In between opening and closing audio tags we used the source tag to embed our mp3 audio file using the src attribute and its media type using the type attribute.

If the browser does not support the audio tag, the text inside the audio tag will be displayed.

Click here to download the above mp3 audio file for practice purposes.

Note: The autoplay attribute will only work when the webpage is executed from a web server.

Embedding Audio Using JavaScript Libraries

There are several javascript libraries available to embed audio in an HTML document. These libraries offer additional features and customization options compared to the audio tag. Some popular javascript audio libraries are:

  • jPlayer: A jQuery plugin that allows you to play and control audio and video files.
  • SoundManager 2: A JavaScript library that provides an easy-to-use API for playing audio files.
  • Howler.js: A JavaScript library that allows you to play and control audio files with an HTML5 audio API fallback for unsupported browsers.

Note: To use the above libraries you must know JavaScript and jQuery.