Play sounds with javascript

Posted on

We’re going to have a button and when we click it we’re going to play a sound.

Source code on github

Demo hosted with gh-pages

Make sound button


<div class='row text-center' style='margin-top: 50px;'>
    <div id="1" class="gridBox btn btn-lg btn-primary">Hey everybody</div>

I’m using sound.js and for starters using code provided from their website, slightly modified for styling


    var preload;

    function init() {
        if (!createjs.Sound.initializeDefaultPlugins()) {

        var assetsPath = "";
        var sounds = [
            {src: "hey_everybody.m4a", id: 1}

        createjs.Sound.alternateExtensions = ["mp3"];   // add other extensions to try loading if the src file extension is not supported
        createjs.Sound.addEventListener("fileload", createjs.proxy(soundLoaded, this)); // add an event listener for when load is completed
        createjs.Sound.registerSounds(sounds, assetsPath);

    function soundLoaded(event) {
        var div = document.getElementById(;

    function stop() {
        if (preload != null) {

    function playSound(target) {
        //Play the sound: play (src, interrupt, delay, offset, loop, volume, pan)
        var instance =, createjs.Sound.INTERRUPT_NONE, 0, 0, false, 1);
        if (instance == null || instance.playState == createjs.Sound.PLAY_FAILED) {
        instance.addEventListener("complete", function (instance) {


    $('.gridBox').on('click', function(){
        }, 2000);


At the end of the function we call init and listen for clicks. Stop the sound after 2 seconds.

Leave a Reply

Your email address will not be published.