使用Javascript音频顺序播放音频声音

使用Javascript音频顺序播放音频声音

本文介绍了使用Javascript音频顺序播放音频声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个基于Web的队列系统,我发现音频方面很困难,例如我想按顺序播放音频

I'm creating a queue system based on web, and i find it difficult on the audio part, i want audio playing sequencely, for example

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 事件:

Simply hold the current index of the audio you're playing,
and increment it in HTMLAudio's ended event :

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 变量之外创建此变量,也可以直接从数组中获取它:

And if you don't want to create this out of scope currentIndex variable, you can also get it directly from your array :

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音频顺序播放音频声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:57