37

OK I've read several answers here but they didn't help me at all (in fact, none of them is being accepted as answer)

Question is how to "Play a beep sound" on "button click"

I am trying to make a website that works on touchscreen device so I want every button click events will play a beep sound, that should be nicer for users who using the website. Beep sound file is here: http://www.soundjay.com/button/beep-07.wav . I only need this work on Google Chrome (supports HTML5)

I understand this need to work on client-side so I tried this:

Javascript:

<script>
    function PlaySound(soundObj) {
        var sound = document.getElementById(soundObj);
        sound.Play();
    }
</script>

HTML

<embed src="/beep.wav" autostart="false" type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />
<asp:LinkButton ID="lbtnExit" runat="server" OnClick="lbtnExit_Click" OnClientClick="PlaySound('beep')" CssClass="btn btn-lg btn-danger" Text="Exit <i class='fa fa-sign-out' style='font-size: 40px'></i>"></asp:LinkButton>

But it doesn't work, nothing happens when I click the button.

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110

7 Answers7

62

You could use an audio tag like this:

    <audio id="audio" src="http://www.soundjay.com/button/beep-07.wav" autoplay="false" ></audio>
    <a onclick="playSound();"> Play</a>
    <script>
    function playSound() {
          var sound = document.getElementById("audio");
          sound.play();
      }
    </script>

Here is a Plunker

Tom Pohl
  • 2,711
  • 3
  • 27
  • 34
netrevisanto
  • 1,091
  • 12
  • 13
  • Thank you. For Internet Explorer 10 use .mp3 instead of .wav – Imran Mohammed Jan 23 '18 at 10:51
  • 1
    According to the [documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) _autostart_ is not an `audio` attribute. Instead it should be _autoplay_. – csr-nontol May 05 '18 at 05:48
  • autoplay="false" is not respected by Firefox 86. Should remove the attribute for it to NOT autoplay. The same happens with the attribute loop. – Adrián E Mar 04 '21 at 13:26
16

Admitting you already have something like <div id='btn'>Click to play!</div> in your html, you could do it as simple as:

$('#btn').click( () => new Audio('mp3/audio.mp3').play() );

This is the best solution IMO because it allow to click multiple times quickly on the button without problem (which is not possible in other answers at the time) and is a one liner.

const audioUrl = 'https://freewavesamples.com/files/Ensoniq-ESQ-1-Piano-C3.wav'

$('.btn').click( () => new Audio(audioUrl).play() ); // that will do the trick !!
body {padding: 16px;}

.btn {
  background: tomato;
  padding:15px;
  border-radius:5px;
  color:#fff;
  cursor: pointer;
  box-shadow: 0 -3px rgba(0,0,0,0.15) inset;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class='btn'>Click to play!</span>

Example on codepen

TOPKAT
  • 6,667
  • 2
  • 44
  • 72
13

This works fine

function playSound () {
    document.getElementById('play').play();
}
<audio id="play" src="http://www.soundjay.com/button/beep-07.wav"></audio>

<button onclick="playSound()">Play</button>
Downgoat
  • 13,771
  • 5
  • 46
  • 69
11

Technically, the following doesn't answer the question about "playing" a beep, but if asking how to "generate" a beep, then consider the following code that I found on this website:

a=new AudioContext()
function beep(vol, freq, duration){
  v=a.createOscillator()
  u=a.createGain()
  v.connect(u)
  v.frequency.value=freq
  v.type="square"
  u.connect(a.destination)
  u.gain.value=vol*0.01
  v.start(a.currentTime)
  v.stop(a.currentTime+duration*0.001)
}

Sample values for the call: beep(20, 100, 30). The aforementioned website includes more details and sound samples.

The sound can be in response to a button click or programmatically generated at will. I have used it in Chrome but have not tried it in other browsers.

Alan M.
  • 1,309
  • 2
  • 19
  • 29
8

With raw JavaScript, you can simply call:

new Audio('sound.wav').play()
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

Been driving me crazy, but with JQuery I found a solution... not really the best way to do it, but it worked properly for me...

function ding() {
      $("body").append('<embed src="/ding.mp3" autostart=false autoplay=false type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />');
      setTimeout(function(){ $("#beep").remove(); },2000);
}

not sure how much of the embed tag is really required, but once it started working, I stopped writing (embed copied from another solution).

Hope this helps someone else (or helps me the next time I forget)

thphoenix
  • 181
  • 4
  • 2
    Urgh, this is clumsy. Why not using `function ding() { new Audio('/ding.mp3').play(); }` ? – TOPKAT Nov 27 '19 at 15:25
0

expanding on Alan M.'s answer, this will prevent console errors if unable to run due to no user event yet

var actx = false;
function beep(vol, freq, duration){
    try{
        if(!actx) actx = new AudioContext();
        v=actx.createOscillator();
        u=actx.createGain();
        v.connect(u);
        v.frequency.value=freq;
        u.connect(actx.destination);
        u.gain.value=vol*0.01;
        v.start(actx.currentTime);
        v.stop(actx.currentTime+duration*0.001);
    }catch{
        // ignore
    }
}
kaioker2
  • 297
  • 3
  • 11