SmartCodingTips

Using the HTML <audio> Tag

The <audio> tag is used to embed audio content such as music or sound effects in a webpage. It supports multiple source formats and playback controls.

Basic Audio Example

A simple audio element with controls:


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

Attributes of <audio>

  • src: Specifies the audio file URL (optional if using <source> elements).
  • controls: Displays playback controls like play, pause, and volume.
  • autoplay: Starts playing the audio automatically (muted audio recommended for autoplay).
  • loop: Repeats the audio indefinitely.
  • muted: Starts the audio muted.
  • preload: Indicates if and how the audio should be loaded when the page loads (values: auto, metadata, none).

Multiple Sources for Compatibility

Providing multiple audio sources in different formats improves browser compatibility.


<audio controls preload="auto">
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>
            

Accessibility Tips

  • Include fallback text between <audio> tags for unsupported browsers.
  • Use captions or transcripts for audio content to improve accessibility.
  • Use the preload attribute wisely to optimize page load.