HTML Audio & Video
HTML DOM Audio Object
The Audio object represents an HTML <audio> element in the DOM. It exposes the HTMLAudioElement interface, which inherits all of the media playback properties, methods and events from HTMLMediaElement. You can obtain an Audio object from an existing element with getElementById() or create one entirely in JavaScript with the new Audio() constructor.
Definition and Usage
An Audio object gives JavaScript full control over audio playback: loading a source, starting and stopping playback, adjusting volume and speed, and reacting to playback events. It can be created without any markup on the page, which makes it ideal for sound effects, notification tones and background music that you trigger programmatically.
The new Audio() constructor returns an HTMLAudioElement that is not attached to the document. Because it is not in the DOM tree, it shows no controls, but it can still load and play sound.
Syntax
// Create a brand-new audio element in JavaScript
let sound = new Audio(url);
// Or access an existing <audio> element already in the page
let audio = document.getElementById("myAudio");The url argument is optional. If provided, it sets the src property of the new audio element so the browser can begin loading the file.
Example: creating and playing audio
<button onclick="playSound()">Play sound</button>
<script>
const sound = new Audio("https://www.w3schools.com/html/horse.mp3");
sound.volume = 0.5; // half volume (0.0 to 1.0)
function playSound() {
// play() returns a Promise you can await or catch
sound.play().catch(err => console.log("Blocked:", err));
}
</script>Calling play() begins playback and returns a Promise. Modern browsers reject that Promise if the browser blocks autoplay, so catching it prevents an unhandled rejection. Because the audio element here is never added to the document, no player UI appears on screen.
Example: handling playback events
const audio = document.getElementById("bgMusic");
audio.addEventListener("play", () => console.log("Started"));
audio.addEventListener("pause", () => console.log("Paused"));
audio.addEventListener("ended", () => console.log("Finished"));
audio.play();
setTimeout(() => audio.pause(), 3000); // pause after 3sMost browsers require a user gesture (such as a click) before audio may play with sound. Attempting to play() without one causes the returned Promise to reject with a NotAllowedError.
