我有以下HTML代码:
<div id="1">Paragraph 1</div>
<div id="2">Paragraph 2</div>
<div id="3">Paragraph 3</div>
<div id="4">Paragraph 4</div>
<div id="5">Paragraph 5</div>
<span id="play">play</span>
我想做的是,当我单击“播放”时,播放第1段的音频,并且在播放时,突出显示该div,然后在背景中加载下一段的音频,以使音频不会停止完全可以加载,并且可以无缝过渡到下一个。现在,当第一段的音频播放完毕时,请取消突出显示该div,然后播放下一段的音频并突出显示它,然后重复该过程,直到完成循环为止。
我认为通过获取音频文件的持续时间并在for循环中播放所有音频,这很容易做到。但这不起作用:
$('#play').on("click",function(){
var total_paragraphs = 7;
function playAudio() {
for (var i = 1; i <= total_paragraphs; i++) {
var audio = new Audio("paragraphs/"+i+".mp3");
var sec, ms;
audio.addEventListener("loadedmetadata", function(_event) {
seconds = audio.duration.toFixed(2),
milliseconds = audio.duration.toFixed(2)*1000;
});
$("#"+i).css("background-color", "red");
audio.play();
audio.onended = function() {
$("#"+i).css("background-color", "white");
};
}
}
playAudio();
});
当我单击“播放”时,所有音频同时播放。似乎所有循环都在同一时间执行。我以为可以延长音频文件的播放时间来延迟循环,但这也不起作用。
我敢肯定有很多简单的方法可以完成我想要的事情。任何帮助,将不胜感激。
答案 0 :(得分:1)
怎么样:
html
<div class="paragraph">Paragraph 1</div>
<div class="paragraph">Paragraph 2</div>
<div class="paragraph">Paragraph 3</div>
<div class="paragraph">Paragraph 4</div>
<div class="paragraph">Paragraph 5</div>
<span id="play">play</span>
jquery
_play = (totalParagraphs, currentParagraph) =>
{
const paragraph = $(`.paragraph:nth-child(${currentParagraph})`)
if (currentParagraph <= totalParagraphs)
{
paragraph.css('background', 'coral');
const audio = new Audio(`paragraphs/${currentParagraph}.mp3`)
audio.play()
audio.onended = () => {
paragraph.css('background', 'white')
_play(totalParagraphs, currentParagraph + 1)
}
}
}
$('#play').on('click', () => {
let totalParagraphs = $('.paragraph').length,
currentParagraph = 1
_play(totalParagraphs, currentParagraph)
})