How does the audio element work in HTML, and what is it used for?

In HTML, you can include sound into your code, using the audio element.

Compatible with audio element, are popular audio formats like mp3, WAV, and OGG.

Example of using the audio element.
(click on the image to open in a new tab)

Running this example will show nothing on the page. But, if you check the page using the developer tools, you can see the audio element is there.

The audio player is not visible on the page without certain attributes.
(click on the image to open in a new tab)

In order to view the audio player, you just include the controls attribute.

The control attribute that makes the audio player visible.
(click on the image to open in a new tab)

The controls attribute allows users to adjust volume, pause, and resume audio playback.

The control attribute allows us to adjust volume and control playback.

If you omit the controls attribute, no controls will be shown.

Besides the src and controls attributes, the audio element has other attributes enhancing its functionality.

One of them is the loop attribute which makes the audio play repeatedly.

The loop attribute makes the audio play repeatedly.
(click on the image to open in a new tab)

With this attribute,the song currently playing will restart automatically upon completion.

Another attribute we can use is the muted attribute.

Including the muted attribute in the audio element will start the audio in a muted state.

That means that when you start the song in the browser, you’ll not hear anything unless you click on the volume icon.

Let’s see an example of using the muted attribute:

The muted attribute starts the audio in muted state.
(click on the image to open in a new tab)

Different browsers support different audio file types.

This is handled by placing source elements inside the audio element; the browser will automatically use the first compatible one.

Below is an example of using multiple source elements for an audio element:

The browser will automatically use the first compatible audio file.
(click on the image to open in a new tab)

The browser tries the ogg format first; if that fails, it falls back to the next audio type.

Although my blog doesn’t support comments, feel free to reply via email or X.

Privacy Policy Lambros Hatzinikolaou © 2024 — Today. All rights reserved.