Notification Sound Using Javascript

In this tutorial I’ll show you how you can play notification sound in your web based application using javascript. You might have listen notification sound on chat application like facebook, Gmail, So here i am going to create that type of thing in very minimal code.

So first of all create a very simple chat box in html, I just have created a very basic layout you can customize as per your need to make it professional.

<h3>Notification Sound Using Javascript</h3>
	<div >
	<b>Chat Box</b>
	<form id="form1">
	<table border=1><tr><td height=200 valign="top">
  <ul class="msgBox">
    <li><b>Rohit:</b> Hello, How Are You?</li>
  </ul>
  </td></tr>
  <tr><td>
  <input type="hidden" name="fname" value="form1"> 
  <input type="text" name="name" placeholder="Enter Name" required="required" style="width:100px;"> 
  <input type="text" name="msg" placeholder="Enter Msg" required="required">
   <button type="button">Submit</button> 
  </td></tr></table></form>
</div>

Now place sound file in your directory in my case i placed noti.mp3 in my project directory



Finally add javascript in your page to create some real time action, Here i used HTML5 audio function in javascript for notification

<script>
  $(function() {
     $("button").click(function() {
     	var name = $.trim($("input[name='name']").val());
        var msg = $.trim($("input[name='msg']").val());
        if(name == '' || msg == '') {
            alert("Please enter required fields");
            return false;
        }
        var audio = new Audio('noti.mp3');
        audio.play();
        $(".msgBox").append("<li><b>"+name+": </b> "+msg+"</li>");
        $("input[name='msg']").val("");
     });
  });
  </script>

The above code i have created a audio object by calling new Audio() method and store all the audio properties in audio variable.

DEMO DOWNLOAD

You can control more audion feature here is the list of available audio function you can use.
http://www.w3schools.com/tags/ref_av_dom.asp

Hope this simple tutorial will help you to create notification sound using javascript to make your web based application more fancy.

If you like this post please don’t forget to subscribe my public note book for more useful stuff