Reputation: 123
I have this HTML code:
<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>
What I want to do is, when I click on "play", the audio for paragraph 1 plays, and while it's playing, highlight this div, and load the next paragraphs audio in background so that the audio doesn't stop at all to load and it's a seamless transition to the next one. Now when the audio for the first paragraph is done playing, unhighlight this div, and then play the next paragraph's audio and highlight it and repeat the process until the loop is done.
I thought this would be easy to do by getting the audio file duration and playing all the audios in a for loop. But this doesn't work:
$('#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();
});
When I click on play, all the audios are played at the same time. Seems like all the loops are executed at the same time. I thought to get the audio file duration to delay the loop but that doesn't work either.
I'm sure there is a lot easier way to do what I want. Any help would be appreciated.
Upvotes: 0
Views: 232
Reputation: 124
how about:
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)
})
Upvotes: 1