如何使用JavaScript按顺序播放多个声音

How to play a number of sounds in sequence with JavaScript?

本文关键字:声音 播放 顺序 何使用 JavaScript      更新时间:2023-09-26

我有一些mp3声音(I, y, e等)。我想播放他们在一个序列(即没有任何暂停之间),当用户按下按钮基于用户在文本字段中给出的单词(例如,eye)。

我知道音频可以使用以下HTML来播放:

<source type="audio/mpeg" id="mp3"></source>

你可以使用ended事件在前一个声音完成时播放下一个声音:

var i = document.getElementById("i"),
    y = document.getElementById("y"),
    e = document.getElementById("e");
i.addEventListener("ended", function() {
  y.play();
}, false);
y.addEventListener("ended", function() {
  e.play();
}, false);
i.play();
<audio id="i" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_unrounded_vowel.mp3"  controls></audio>
<audio id="y" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_rounded_vowel.mp3" controls></audio>
<audio id="e" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close-mid_front_unrounded_vowel.mp3" controls></audio>

…但请注意,这些音频文件在音频数据的中有暂停。所以你要么必须编辑文件,要么必须在它们上设置音频位置,可能是每个声音的自定义值,你必须响应timeupdate事件,而不是在音频中观看你认为声音实际上结束的点,在该点停止播放并开始下一个。

下面是截断i声音的第一部分和最后一部分的示例:

var i = document.getElementById("i"),
    y = document.getElementById("y"),
    e = document.getElementById("e");
var istarted = false, istop;
i.addEventListener("canplay", function() {
  this.currentTime = 0.02;
  istop = this.duration - 0.6;
  if (!istarted) {
    this.play();
    istarted = true;
  }
});
i.addEventListener("timeupdate", function() {
  if (this.currentTime > istop) {
    this.pause();
    y.play();
  }
}, false);
y.addEventListener("ended", function() {
  e.play();
}, false);
<audio id="i" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_unrounded_vowel.mp3"  controls></audio>
<audio id="y" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_rounded_vowel.mp3" controls></audio>
<audio id="e" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close-mid_front_unrounded_vowel.mp3" controls></audio>

上面两个都不是很健壮,可能应该等待确保媒体被加载,等等。它们只是指向相关的事情去做。

还要注意的是,timeupdate是一个有点"尽力而为"的事件,它不会是超精确的