How to use the HTML5 Audio API

· Category: HTML & CSS

Short answer

The HTML5 audio element provides built-in media controls. Its JavaScript API exposes methods like play(), pause(), and properties like currentTime and volume.

Steps

  1. Add an audio tag with controls and source files.
  2. Access the element in JavaScript to call playback methods.
  3. Listen for events like play, pause, ended, and timeupdate.

Example

<audio id="player" src="song.mp3"></audio>
<button onclick="document.getElementById('player').play()">Play</button>

Tips

  • Provide multiple source elements for format compatibility.
  • Use the preload attribute to hint loading behavior.
  • Customize the UI by hiding default controls and building your own.