gpt4 book ai didi

javascript - 使用 for 循环连续播放音频文件

转载 作者:行者123 更新时间:2023-12-02 23:21:59 24 4
gpt4 key购买 nike

我有这个 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();

});

当我点击播放时,所有音频都会同时播放。似乎所有循环都是同时执行的。我想获取音频文件持续时间来延迟循环,但这也不起作用。

我确信有更简单的方法可以做我想做的事。任何帮助,将不胜感激。

最佳答案

怎么样:

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)

})

关于javascript - 使用 for 循环连续播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com