播放一系列声音文件

时间:2013-03-28 00:51:56

标签: javascript html5

我正在尝试将变量传递给JavaScript函数并使用HTML5 <audio>元素播放它。

如果我将一个字符串参数传递给该函数,那么这只是一个文件而我会播放它。但是如果我传递一个数组,我想逐个播放整个数组。

这是我的基本想法:

function playSound(sound) {
    var audio = document.getElementById('sound');
    if(sound instanceof Array) {
        // Play the whole array
    }
    else {
        // Play only one file
        audio.src = sound;
        audio.play();
    }
}

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您可以继续在循环中呼叫playSound并将呼叫绑定到onended

if (sound instanceof Array) {
    audio.src = sound.shift();
    audio.play;
    if (sound.length) {
        audio.addEventListener('ended', function () {
            playSound(sound);
        });
    }
}