How to play an audio in JavaScript

Marika Lam
Sep 29, 2022

Here is the JavaScript.

function playAudio(url) {
new Audio(url).play();
}

Here is the HTML.

<img src="image.png" onclick="playAudio('mysound.mp3')">

If you experience a delay, use var audio = new Audio(url); once on page load. Then trigger it by audio.currentTime = 0; audio.play();. Resetting current time is only needed if the sound is played in short bursts.

Amazon Links to “Must-Haves” as a WFH Software Engineer 🙂💻

24-inch budget-friendly monitor, Portable monitor, Laptop stand, Waterproof desk mat, Keyboard cleaning gel, Six-outlet wall charger and surge protector,, Wi-Fi extender, Blue-light–blocking glasses, Memory foam gel pad, Foam footrest

Courses to learn more about datastructures/algorithms ✍️

Stanford, Duke, UCSD

Courses to learn more about databases 👓

DB Foundations, Data Scientists specialization

Courses to learn more about React 🧢

Full-Stack WebDev, Front-End WebDev with React, IBM Full Stack

--

--