簡體   English   中英

javascript在事件上發出多種聲音

[英]javascript multiple sounds fired on event

我正在研究一個簡單的腳本,嘗試使用js在html中放置2種或更多聲音,並在某些事件(來自游戲)中通過回調觸發它們。

我設法使其具有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();
            },

        };

這是根據我發現的教程改編而成的實現。

// 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM