Immediate play sound on button click in HTML page
If you only need to support recent browsers, then HTML 5 offers you the Audio
object
to load/buffer your sound:
var snd = new Audio("file.wav");
to play the sound:
snd.play();
to re-cue it to the beginning (so that you can play it again):
snd.currentTime=0;
This answer https://stackoverflow.com/a/7620930/1459653 by @klaustopher (https://stackoverflow.com/users/767272/klaustopher) helped me. He wrote:
HTML5 has the new
<audio>
-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface:
<audio id="sound1" src="yoursound.mp3" preload="auto"></audio> <button onclick="document.getElementById('sound1').play();">Play it</button>
Here's how I implemented his advice so that clicking on the Font Awesome icon "fa-volume-up" (located on the Web page after "mule.") results in "donkey2.mp3" sound playing (note: mp3 doesn't play in all browsers).
<p>In short, you're treated like a whole person, instead of a rented mule. <audio id="sound1" src="assets/donkey2.mp3" preload="auto"></audio><a class="icon fa-volume-up" onclick="document.getElementById('sound1').play();"></a>