HTML - Audio

The HTML <audio> element is used to embed audio content in a web page. It supports various attributes that allow you to control the playback and appearance of the audio player. Here's an example of using the <audio> tag with some commonly used attributes:

<audio src="audio-file.mp3" controls autoplay loop preload="auto">
  Your browser does not support the audio element.
</audio>

In the example above, we have the following attributes:

  • src: Specifies the URL of the audio file to be played. You can provide the file path or a URL to the audio file.
  • controls: Enables the default audio controls (play, pause, volume control, etc.) to be displayed in the browser. Users can interact with these controls to control playback.
  • autoplay: Starts playing the audio automatically when the page loads. However, note that autoplay behavior is subject to browser restrictions and may require user interaction.
  • loop: Causes the audio to repeat playback indefinitely.
  • preload: Specifies how the browser should load the audio file. The value "auto" indicates that the browser should determine the best strategy for preloading the audio.

The <audio> element allows fallback content to be displayed in browsers that do not support the audio element. In the example above, the text "Your browser does not support the audio element." will be shown in browsers that don't support <audio>.

Additionally, you can include multiple <source> elements within the <audio> tag to provide alternative audio formats. This ensures compatibility across different browsers that support different audio formats. Here's an example:

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

In this case, the <source> elements specify different audio file formats (MP3 and Ogg) with their corresponding MIME types. The browser will try to play the audio in the first supported format.

Feel free to replace "audio-file.mp3" and "audio-file.ogg" with the actual URLs or file paths to your audio files.