How to add and play Audio with JavaScript

JavaScript allows to add an Audio file that is very helpful depending on your needs. For example, if you want to make a web application of that plays audio when user press a key from the keyboard or just use the left click, then JavaScript can help you do that. We will soon try to build a quick web app for the demo. In the mean time, let’s learn how you can add the audio.

How do I Play an Audio with JavaScrip

var audio = new Audio('URLofTheAudioFile');;

Wasn’t it easy? just 2 lines of code and Audio is ready to play. Let’s play audio when user click with the help of JavaScript and jQuery.

Playing Audio When User User Left Click on a Button With jQuery and JavaScript

<!DOCTYPE html>

      <title>Playing Audio with JS and jQuery</title>

      <!-- CSS Styling. Just to make the button more visible -->

           text-align: center;
           font-size: 2rem;
           width: 200px;
           height: 150px;
           margin:300px 500px;


<!-- We will use this button to play audio      -->
       <button>Play Audio</button>

<!-- jQuery CDN Google's hosted Link -->

<script src=""></script>

<!-- Coding to play Sound with Button Click -->

<script type="text/javascript">
    var music = new Audio('');;


Here is the Output file.

If you have any question that you would like to ask, feel free to comment.