Open In App

How to Make a Beep Sound in JavaScript?

Last Updated : 15 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To make a beep sound in JavaScript, you can use the Audio object to play a sound file.

Approach: Using Audio Function

Use the Audio function in Javascript to load the audio file. This HTML document creates a simple web page with a heading and a button. When the button is clicked, the play() function is executed, which creates a new audio object using a specified MP3 file URL and plays the sound, providing an interactive audio experience to users.

Example: This example shows the implementation of the above-mentioned approach.

html
<!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() {
            let audio = new Audio(
'https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');
            audio.play();
        }
    </script>
</body>
  
</html>

Output:

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

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>

    <audio id="chatAudio" >
        <source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3" 
        type="audio/mpeg">
    </audio>
    <button onclick="play()">Press Here!</button>
 
    <script>
        let audio = document.getElementById('chatAudio');
        function play(){
            audio.play()
        }
    </script>
</body>
  
</html>

Output:


Next Article

Similar Reads