Play an audio file (sound/music)
This is the simplest way to play an audio file without including an audio HTML element in a page.
let track = new Audio("beep.mp4");
let button = document.querySelector("button");
button.addEventListener("click", async (event) => {
await playAudio(track);
});
async function playAudio(track) {
track.volume = 0.2;
try {
await track.play();
} catch (error) {
console.error(error);
}
} Demo
This example will play an mp4 audio file at low volume when you press the button. It is a checkout scanner beep!
Explanation
The Audio() constructor creates and returns a new HTMLAudioElement which can be used to play audio the same way as the audio element. It can be can be used offscreen to manage and play audio.
Memory usage and management
The element is removed from memory by the JavaScript runtime’s garbage collection mechanism only if all references are deleted and playback is finished.