I have this HTML code:
<div class="paragraph" id="1">Paragraph 1</div>
<div class="paragraph" id="2">Paragraph 2</div>
<div class="paragraph" id="3">Paragraph 3</div>
<div class="paragraph" id="4">Paragraph 4</div>
<div class="paragraph" id="5">Paragraph 5</div>
<span id="play">play</span>
And this JavaScript code:
function playAudio(totalParagraphs, currentParagraph) {
var paragraph = $(".paragraph#"+currentParagraph);
if(currentParagraph <= totalParagraphs) {
paragraph.css('background', 'red');
var audio = new Audio("audios/"+currentParagraph+".mp3");
audio.play();
audio.onended = () => {
paragraph.css('background', 'white');
playAudio(totalParagraphs, currentParagraph + 1);
}
}
}
$('#play').on('click', () => {
let totalParagraphs = $('.paragraph').length, currentParagraph = 1;
playAudio(totalParagraphs, currentParagraph);
});
When I click on the play
, the playAudio()
function is fired. In playAudio()
function, it loads the audio for paragraph 1 and plays it, then when the audio ends, playAudio()
is fired again to play the audio for the next paragraph and so on. This works perfectly on desktop browsers but does not on mobile browsers. No matter what mobile browser I use, Safari, Chrome, Mozilla, the same problem occurs.
On mobile, only the first audio plays and not the next.
I even tried to add an alert before audio.play()
and I get the alert on mobile but the audio doesn't play.
I tried to search for a solution online but did not get a working one for my case. Any solutions would be appreciated.