How to add and play Audio with JavaScript

Please Subscribe to our YouTube Channel

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'); 
audio.play();
 

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>
<html>
  <head>

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

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

        <style>
          button{
           text-align: center;
           font-size: 2rem;
           width: 200px;
           height: 150px;
           margin:300px 500px;
          }
        </style>

  </head>
    <body>

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

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<script type="text/javascript">
  $('button').click(function(){
    var music = new Audio('/wp-content/uploads/2018/12/feelinggood.mp3');
    music.play();
  });
</script>

    </body>
</html>

Here is the Output file.

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