javascript несколько звуков, запускаемых при событии

Я работаю над простым скриптом, пытаясь поместить 2 или более звуков в html с помощью js и запускать их при определенных событиях (из игры) с обратными вызовами.

Мне удалось заставить его работать с 1 звуком, но он терпит неудачу, когда я пытаюсь добавить второй или несколько, есть идеи?

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

и обратные вызовы

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

        };

person yeboos    schedule 13.06.2015    source источник
comment
Это может воспроизводить только один звук за раз. Вы можете сделать что-то вроде этого: blog.sklambert.com/   -  person Jonathan    schedule 13.06.2015


Ответы (1)


Вот реализация, адаптированная из учебника, который я нашел.

// 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();
person Jonathan    schedule 13.06.2015