Ben Borgers / Posts /

How to play an audio file with JavaScript

January 30, 2021 by @benborgers

Playing a sound with pure javascript is surprisingly easy. First, you need a URL to the audio file you want to play. We'll use this one:

https://www.w3schools.com/html/horse.mp3

Now, all it takes is two lines of code to play that sound file:

const sound = new Audio('https://www.w3schools.com/html/horse.mp3')
sound.play()

A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Please use this form to let me know or ask for help!

Loading...