0
votes

Playing a looping audio in HTML5 is as simple as this:

<html>
<head></head>
<body>
    <audio controls autoplay loop>
      <source src="../media/audio/timer.ogg" type="audio/ogg" />
      <source src="../media/audio/timer.mp3" type="audio/mpeg" />
    </audio>
</body>
</html>

Ok, that does not work on Firefox but there are tricks. That example works on Safari and Chrome, but that's not the question. The thing is that I'm loading the same code on a certain div using jQuery's load() method: $('#mydiv').load(url, function() {..});

When that piece of HTML code is loaded, the div is shown and the audio file is properly heard (autoplay)... but it won't loop! While it loops on the small html example seen above, the same code coming from an AJAX call won't loop at all. And I know it's there, in the DOM. Am I missing something?

1

1 Answers

1
votes

An alternative way is to remove loop attribute and reset the currentTime attribute of the new <audio> element when onended event occurs. A simple jquery example could be smthg like:

/* make ajax call and append audio element */
$('audio').on('ended', function() {
   this.currentTime = 0;
});

in this way the audio will restart automatically every time he reches the end (and this behaviour is almost the same of a native loop).