๐ŸŽ“ A1Learner
๐Ÿ”
0 of 50 lessons completed

HTML Audio

The audio element puts a sound player on a page. Its controls attribute adds play and pause buttons.

A player with controls

The controls attribute adds the player buttons. The player plays nothing with no sound file.

<audio controls></audio>

Naming a sound file

The source element names the sound file. The type value tells the browser the file kind. This lesson ships no sound file, so the player still plays nothing.

<audio controls>
  <source src="song.mp3" type="audio/mpeg">
</audio>

Fallback text

Fallback text sits inside the audio element. A browser that cannot play audio shows this text instead.

<audio controls>
  This browser cannot play audio.
</audio>

A player under a label

A short line above the player says what it holds. The player itself shows only its buttons.

<p>Listen to the harbour sounds.</p>
<audio controls></audio>

Example

<!DOCTYPE html>
<html lang="en">
<head>
<title>Harbour Sounds</title>
</head>
<body>
<h1>Harbour Sounds</h1>
<p>Press play to listen.</p>
<audio controls>
  This browser cannot play audio.
</audio>
<p>The player has no sound file. It plays nothing for now.</p>
</body>
</html>

Key points

  • audio: an element that puts a sound player on a page
  • controls: an attribute that adds player buttons
  • source: an element that names a media file for a player
  • Several source elements can sit in one player
  • The browser tries source elements in order

In this example, the heading and the first paragraph introduce the sounds. The audio element holds a player with controls. The fallback text inside the player stays hidden in a supporting browser. The last paragraph states plainly that the player has no sound file.

Note

The closing example has no sound file. It plays nothing.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which element names the sound file for an audio player?