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
- Add an
audiotag withcontrolsand source files. - Access the element in JavaScript to call playback methods.
- Listen for events like
play,pause,ended, andtimeupdate.
Example
<audio id="player" src="song.mp3"></audio>
<button onclick="document.getElementById('player').play()">Play</button>
Tips
- Provide multiple
sourceelements for format compatibility. - Use the
preloadattribute to hint loading behavior. - Customize the UI by hiding default controls and building your own.