如何在HTML中播放多个mp3 /歌曲?

时间:2016-02-03 10:16:04

标签: javascript html html5-audio

我试图让我的网站播放多首mp3 /歌曲,但它继续播放音轨1,但我希望它能同时播放所有3首歌曲。

这就是我目前所拥有的:

<audio loop autoplay controls>
    <source src="soundtrack1.mp3" type="audio/mpeg" loop="true">
    <source src="soundtrack2.mp3" type="audio/mpeg" loop="true">
    <source src="soundtrack3.mp3" type="audio/mpeg" loop="true">
    Your browser does not support the audio element.
</audio>

2 个答案:

答案 0 :(得分:3)

因此HTML非常简单1,2,3

<audio src="..." id="song1" volume="0.1" style="display: none;"></audio>
<audio src="..." id="song2" volume="0.1" style="display: none;"></audio>
<audio src="..." id="song3" volume="0.1" style="display: none;"></audio>

它背后的JS魔法:

for(var i = 1; i <= 3; i++)
{
    document.querySelector("#song" + i)[0].play();
}

答案 1 :(得分:0)

如果您只想在Javascript中执行此操作:

var song1  = new Audio();
var src1  = document.createElement("source");
src1.type = "audio/mpeg";
src1.src  = "soundtrack1.mp3";
song1.appendChild(src1);
song1.play();

var song2  = new Audio();
var src2  = document.createElement("source");
src2.type = "audio/mpeg";
src2.src  = "soundtrack2.mp3";
song2.appendChild(src2);
song2.play();