How to make a beep sound in JavaScript ?

A beep sound in a website can be used for the following tasks:

  • Alert notification
  • Make the website more interactive

There can be many more use cases of these sounds. It all depends on one’s creativity and needs. Usually, we create a function in Javascript and call that function whenever required. In this tutorial, we are using a button to play the “beep” sound using the onclick method.

Method 1: Use Audio function in Javascript to load the audio file.



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
        content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
  
<body>
    <h1>Press the Button</h1>
  
    <button onclick="play()">Press Here!</button>
  
    <script>
        function play() {
            var audio = new Audio(
            audio.play();
        }
    </script>
</body>
</html>

chevron_right


Output:

Method 2: Use the audio tag in html and play it using Javascript.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
        content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
  
<body>
    <h1>Press the Button</h1>
  
    <audio id="chatAudio" >
        <source src=
        type="audio/mpeg">
    </audio>
    <button onclick="play()">Press Here!</button>
   
    <script>
        var audio = document.getElementById('chatAudio');
        function play(){
            audio.play()
        }
    </script>
</body>
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.