javascript multiple sounds fired on event

128 views Asked by At

I'm working on a simple script, trying to put 2 or more sounds in html using js and fire them on certain events (from a game) with callbacks.

I managed to get it working with 1 sound, but it fails when i try to add the second one or more, any ideas?

            var audio = new Audio("audio.wav");
        audio.addEventListener('ended', function()
        {
            this.currentTime = 0;
            this.play();
        }, false);

and callbacks

            {
            Start: function()
            {
                audio.play();
            },
            Stop: function()
            {
                audio.pause();
            },

        };
1

There are 1 answers

0
Jonathan On

Here's an implementation adapted from a tutorial I found.

// A sound pool to use for the sound effects.
// http://blog.sklambert.com/html5-canvas-game-html5-audio-and-finishing-touches/#adding-html-audio
function SoundPool(filename, volume, maxSize) {
    var pool = [];
    this.pool = pool;
    var currSound = 0;
    var that = this;

    // Populates the pool array with the given sound.
    for (var i = 0; i < maxSize; i++) {
        var sound = new Audio(filename);
        sound.volume = volume;
        pool[i] = sound;
    }

    this.setVolume = function setVolume(volume) {
        for (var i = 0; i < that.pool.length; i++) {
            that.pool[i].volume = volume;
        }
    };

    this.mute = function mute(state) {
        for (var i = 0; i < that.pool.length; i++) {
            // State: toggle, true or false.
            if (typeof state == "undefined")
                that.pool[i].muted = !that.pool[i].muted;
            else
                that.pool[i].muted = state;
        }
    };

    // Plays a sound.
    this.play = function () {
        if (pool[currSound].currentTime == 0 || pool[currSound].ended) {
            pool[currSound].play();
        }
        currSound = (currSound + 1) % maxSize;
    };
}

var laserSound = new SoundPool("sound/effects/laser.wav", 0.5, 300);

laserSound.play();