javascript - 使用javascript音频顺序播放音频声音

标签 javascript html audio

我正在创建一个基于 web 的队列系统,我发现在音频部分很难,例如我想要按顺序播放音频

var sounds = [
    new Audio("/audios/ding.wav"),
    new Audio("/audios/nomor_antrian.wav")
];

for (var i=0; i<sounds.length; i++) {
    sounds[i].play();

    # If sounds[i] is stoped play sounds[i+1] <- what function in here
}

最佳答案

只需按住您正在播放的音频的当前索引,
并在 HTMLAudio 的 ended 中增加它事件:

var url = "https://dl.dropboxusercontent.com/s/";
var sounds = [
  new Audio(url + "kbgd2jm7ezk3u3x/hihat.mp3"),
  new Audio(url + "h2j6vm17r07jf03/snare.mp3"),
  new Audio(url + "h8pvqqol3ovyle8/tom.mp3"),
  new Audio(url + "1cdwpm3gca9mlo0/kick.mp3")
];
var currentIndex = 0; // keep track of the current index
sounds.forEach(function(sound) {
  sound.onended = onended; // add the same event listener for all audios in our array
});

function onended(evt) {
  currentIndex = (currentIndex + 1) % sounds.length; // increment our index
  sounds[currentIndex].play(); // play the next sound
}
btn.onclick = sounds[0].play.bind(sounds[0]);
<button id="btn">play</button>

如果你不想创建这个超出范围的 currentIndex 变量,你也可以直接从你的数组中获取它:

var url = "https://dl.dropboxusercontent.com/s/";
var sounds = [
  new Audio(url + "kbgd2jm7ezk3u3x/hihat.mp3"),
  new Audio(url + "h2j6vm17r07jf03/snare.mp3"),
  new Audio(url + "h8pvqqol3ovyle8/tom.mp3"),
  new Audio(url + "1cdwpm3gca9mlo0/kick.mp3")
];
sounds.forEach(function(sound) {
  sound.onended = onended;
});

function onended(evt) {
  var currentIndex = (sounds.indexOf(this) + 1) % sounds.length; // get and increment our index
  sounds[currentIndex].play(); // play the next sound
}
btn.onclick = sounds[0].play.bind(sounds[0]);
<button id="btn">play</button>

关于javascript - 使用javascript音频顺序播放音频声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45951416/

相关文章:

winapi - 实现类似语音服务器的teamspeak

python - 在 jupyter notebook 中用 python 循环播放声音

javascript - 使用 JQuery 包装元素

javascript - 添加 "undefined"时 Dropzone JS 抛出 "error event"

javascript - 单击一次页面链接时,导航/汉堡包图标消失

数据库中的 HTML 标记不起作用

javascript - Angular.js 常量问题?

javascript - 通过 npm run build 将脚本和 css 引用替换为 HTML 中的内容

javascript - 在 Firefox 中禁用通知的警报声音

actionscript-3 - Actionscript 3 - 使用循环嵌入声音文件数组