docs.rodeo

MDN Web Docs mirror

{{HTMLSidebar}} 

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the {{HTMLElement("source")}}  element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a {{domxref("MediaStream")}} .

{{EmbedInteractiveExample("pages/tabbed/audio.html","tabbed-standard")}} 

The above example shows basic usage of the <audio> element. In a similar manner to the {{htmlelement("img")}}  element, we include a path to the media we want to embed inside the src attribute; we can include other attributes to specify information such as whether we want it to autoplay and loop, whether we want to show the browser’s default audio controls, etc.

The content inside the opening and closing <audio></audio> tags is shown as a fallback in browsers that don’t support the element.

Attributes

This element’s attributes include the global attributes.

Events

Event name Fired when
`{{domxref("ScriptProcessorNode/audioprocess_event", "audioprocess")}}`  The input buffer of a `{{DOMxRef("ScriptProcessorNode")}}`  is ready to be processed.
`{{domxref("HTMLMediaElement.canplay_event", 'canplay')}}`  The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
`{{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}}`  The browser estimates it can play the media up to its end without stopping for content buffering.
`{{domxref("OfflineAudioContext/complete_event", "complete")}}`  The rendering of an `{{DOMxRef("OfflineAudioContext")}}`  is terminated.
`{{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}}`  The duration attribute has been updated.
`{{domxref("HTMLMediaElement.emptied_event", 'emptied')}}`  The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the `{{domxref("HTMLMediaElement.load")}}`  method is called to reload it.
`{{domxref("HTMLMediaElement.ended_event", 'ended')}}`  Playback has stopped because the end of the media was reached.
`{{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}}`  The first frame of the media has finished loading.
`{{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}}`  The metadata has been loaded.
`{{domxref("HTMLMediaElement.loadstart_event", 'loadstart')}}`  Fired when the browser has started to load the resource.
`{{domxref("HTMLMediaElement.pause_event", 'pause')}}`  Playback has been paused.
`{{domxref("HTMLMediaElement.play_event", 'play')}}`  Playback has begun.
`{{domxref("HTMLMediaElement.playing_event", 'playing')}}`  Playback is ready to start after having been paused or delayed due to lack of data.
`{{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}}`  The playback rate has changed.
`{{domxref("HTMLMediaElement.seeked_event", 'seeked')}}`  A seek operation completed.
`{{domxref("HTMLMediaElement.seeking_event", 'seeking')}}`  A seek operation began.
`{{domxref("HTMLMediaElement.stalled_event", 'stalled')}}`  The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
`{{domxref("HTMLMediaElement.suspend_event", 'suspend')}}`  Media data loading has been suspended.
`{{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}}`  The time indicated by the currentTime attribute has been updated.
`{{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}}`  The volume has changed.
`{{domxref("HTMLMediaElement.waiting_event", 'waiting')}}`  Playback has stopped because of a temporary lack of data

Usage notes

Browsers don’t all support the same file types and audio codecs; you can provide multiple sources inside nested {{htmlelement("source")}}  elements, and the browser will then use the first one it understands:

<audio controls>
  <source src="myAudio.mp3" type="audio/mpeg" />
  <source src="myAudio.ogg" type="audio/ogg" />
  <p>
    Download <a href="myAudio.mp3" download="myAudio.mp3">MP3</a> or
    <a href="myAudio.ogg" download="myAudio.ogg">OGG</a> audio.
  </p>
</audio>

The audio source can be set to any valid URL, including HTTP(S) URLs and Data URLs. When using HTTP(S) URLs, be aware that the browser’s caching behavior will affect how often the file is requested from the server. Data URLs embed the audio data directly in the HTML, which can be useful for small audio files but isn’t recommended for larger files as it increases the HTML file size.

You can also use the Web Audio API to directly generate and manipulate audio streams from JavaScript code rather than streaming pre-existing audio files. You can set the srcObject in JavaScript to a {{domxref("MediaStream")}}  object. This is commonly used for live audio streams or real-time audio processing.

const audioElement = document.querySelector("audio");
navigator.mediaDevices
  .getUserMedia({ audio: true })
  .then((stream) => {
    audioElement.srcObject = stream;
  })
  .catch((error) => {
    console.error("Error accessing the microphone", error);
  });

Note that MediaStream sources have limitations: they are not seekable and only support a limited set of codecs.

We offer a substantive and thorough guide to media file types and the audio codecs that can be used within them. Also available is a guide to the codecs supported for video.

Other usage notes:

A good general source of information on using HTML <audio> is the HTML video and audio beginner’s tutorial.

Styling with CSS

The <audio> element has no intrinsic visual output of its own unless the controls attribute is specified, in which case the browser’s default controls are shown.

The default controls have a {{cssxref("display")}}  value of inline by default, and it is often a good idea to set the value to block to improve control over positioning and layout, unless you want it to sit within a text block or similar.

You can style the default controls with properties that affect the block as a single unit, so for example you can give it a {{cssxref("border")}}  and {{cssxref("border-radius")}} , {{cssxref("padding")}} , {{cssxref("margin")}} , etc. You can’t however style the individual components inside the audio player (e.g. change the button size or icons, change the font, etc.), and the controls are different across the different browsers.

To get a consistent look and feel across browsers, you’ll need to create custom controls; these can be marked up and styled in whatever way you want, and then JavaScript can be used along with the {{domxref("HTMLMediaElement")}}  API to wire up their functionality.

Video player styling basics provides some useful styling techniques — it is written in the context of <video>, but much of it is equally applicable to <audio>.

Detecting addition and removal of tracks

You can detect when tracks are added to and removed from an <audio> element using the {{domxref("AudioTrackList/addtrack_event", "addtrack")}}  and {{domxref("AudioTrackList/removetrack_event", "removetrack")}}  events. However, these events aren’t sent directly to the <audio> element itself. Instead, they’re sent to the track list object within the <audio> element’s {{domxref("HTMLMediaElement")}}  that corresponds to the type of track that was added to the element:

[!NOTE] Even though it’s an <audio> element, it still has video and text track lists, and can in fact be used to present video, although the user interface implications can be odd.

For example, to detect when audio tracks are added to or removed from an <audio> element, you can use code like this:

const elem = document.querySelector("audio");

elem.audioTrackList.onaddtrack = (event) => {
  trackEditor.addTrack(event.track);
};

elem.audioTrackList.onremovetrack = (event) => {
  trackEditor.removeTrack(event.track);
};

This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor’s list of available tracks.

You can also use {{domxref("EventTarget.addEventListener", "addEventListener()")}}  to listen for the {{domxref("AudioTrackList/addtrack_event", "addtrack")}}  and {{domxref("AudioTrackList/removetrack_event", "removetrack")}}  events.

Accessibility

Audio with spoken dialog should provide both captions and transcripts that accurately describe its content. Captions, which are specified using WebVTT, allow people who are hearing impaired to understand an audio recording’s content as the recording is being played, while transcripts allow people who need additional time to be able to review the recording’s content at a pace and format that is comfortable for them.

If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source audio.

The <audio> element doesn’t directly support WebVTT. You will have to find a library or framework that provides the capability for you, or write the code to display captions yourself. One option is to play your audio using a {{HTMLElement("video")}}  element, which does support WebVTT.

In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth.

1
00:00:00 --> 00:00:45
[Energetic techno music]

2
00:00:46 --> 00:00:51
Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch?

16
00:00:52 --> 00:01:02
[Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch?

Also it’s a good practice to provide some content (such as the direct download link) as a fallback for viewers who use a browser in which the <audio> element is not supported:

<audio controls>
  <source src="myAudio.mp3" type="audio/mpeg" />
  <source src="myAudio.ogg" type="audio/ogg" />
  <p>
    Download <a href="myAudio.mp3">MP3</a> or
    <a href="myAudio.ogg" download="myAudio.ogg">OGG</a> audio.
  </p>
</audio>

Examples

Basic usage

The following example shows basic usage of the <audio> element to play an OGG file. It will autoplay due to the autoplay attribute—if the page has permission to do so—and also includes fallback content.

<!-- Basic audio playback -->
<audio src="AudioTest.ogg" autoplay>
  <a href="AudioTest.ogg" download="AudioTest.ogg">Download OGG audio</a>.
</audio>

For details on when autoplay works, how to get permission to use autoplay, and how and when it’s appropriate to use autoplay, see our autoplay guide.

<audio> element with <source> element

This example specifies which audio track to embed using the src attribute on a nested <source> element rather than directly on the <audio> element. It is always useful to include the file’s MIME type inside the type attribute, as the browser is able to instantly tell if it can play that file, and not waste time on it if not.

<audio controls>
  <source src="foo.wav" type="audio/wav" />
  <a href="foo.wav" download="foo.wav">Download WAV audio</a>.
</audio>

<audio> with multiple <source> elements

This example includes multiple <source> elements. The browser tries to load the first source element (Opus) if it is able to play it; if not it falls back to the second (Vorbis) and finally back to MP3:

<audio controls>
  <source src="foo.opus" type="audio/ogg; codecs=opus" />
  <source src="foo.ogg" type="audio/ogg; codecs=vorbis" />
  <source src="foo.mp3" type="audio/mpeg" />
</audio>

Technical summary

Content categories Flow content, phrasing content, embedded content. If it has a controls attribute: interactive content and palpable content.
Permitted content If the element has a src attribute: zero or more `{{HTMLElement("track")}}`  elements followed by transparent content that contains no <audio> or `{{HTMLElement("video")}}`  media elements.
Else: zero or more `{{HTMLElement("source")}}`  elements followed by zero or more `{{HTMLElement("track")}}`  elements followed by transparent content that contains no <audio> or `{{HTMLElement("video")}}`  media elements.
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts embedded content.
Implicit ARIA role No corresponding role
Permitted ARIA roles application
DOM interface `{{domxref("HTMLAudioElement")}}` 

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN