4 minutes read

Sound may be an important addition to some websites. If used wisely, music and voice files, as well as a built-in player, can help the visitor relax, catch the vibe, and better interact with the site. In this topic, you will learn how to add sound to your web pages.

Syntax

Until recently, developers could only add sound files to web pages via the <bgsound> tag. It set the audio as a background sound but, unfortunately, gave the user no control over it yet. To solve this problem, a new tag <audio> was added to the fifth version of the HTML standard.

Let's take a look at how we can add audio to a web page using the latest HTML5 features.

The <audio> tag is used to embed audio content into web pages in the following way:

<audio src="media/example.mp3"></audio>

It can also take a nested <source> tag and offer the same audio recording in different formats:

<audio>
  <source src="media/example.mp3" type="audio/mpeg">
  <source src="media/example.ogg" type="audio/ogg">
</audio>

The path to the audio file can be set both through the src attribute and the nested <source> tag. The latter option is used to make sure that the content plays in browsers supporting different formats.

Attributes of tags

The <audio> tag may have several attributes, which control playback and audio settings. Consider some of the most commonly used ones:

  • src indicates the path to the file that's played;

  • controls displays the audio player control interface (playback and pause buttons, volume slider);

  • autoplay is responsible for automatic playback of the file immediately after the page is loaded;

  • loop cycles the audio file;

  • muted mutes the sound when playing an audio file.

In one of the syntax examples above, you may have noticed the type attribute, which should always be used with the <source> tag. It allows the browser to choose and play the compatible kind of media file. Here is a table of media file extensions and types:

File Format

Media Type

MP3

audio/mpeg

OGG

audio/ogg

WAV

audio/wav

Sound controls will appear on the web page only if the controls attribute is specified:

<audio controls src="media/example.mp3"></audio>

Each browser displays this element in its own way, though:

Four different browsers audio players

Conclusion

In this lesson, you've learned how to add audio to your web pages and to use some advanced audio control features offered by HTML5. Now you can let visitors appreciate your website in a whole new light – or a whole new sound, to be exact. Congratulations!

365 learners liked this piece of theory. 5 didn't like it. What about you?
Report a typo