Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat html5 audio

Please read fully before answering (thank you):

I am wanting to seamlessly repeat a track (say 10secs) a given number of times (say 3 times) smoothly by:

  1. Extracting the audio from a given audio player - not required, loaded a .wav from a server etc is fine
  2. Concatenating the audio n times (adding the track onto the end of itself)
  3. Playing the result in a new player

How could 2 be done? An example would be great but 2 is the most puzzling.

Note: Setting the original player to repeat itself etc is not an option as it's not smooth on most browsers.

like image 399
James Avatar asked Feb 13 '26 10:02

James


2 Answers

The loop attribute is a boolean attribute.

When present, it specifies that the audio will start over again, every time it is finished.

<!DOCTYPE html>
<html>
<body>

<audio controls loop>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<p><strong>Note:</strong> The audio tag is not supported in Internet Explorer 8 and earlier versions.</p>

</body>
</html>

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_audio_loop

like image 76
Евгений Сарычев Avatar answered Feb 15 '26 22:02

Евгений Сарычев


O_o This question is old why did StackOverflow show me this.

Well a simple way to do this is to listen on ended an start playing again.

function play(audio, times, ended) {
    if (times <= 0) {
        return;
    }
    var played = 0;
    audio.addEventListener("ended", function() {
        played++;
        if (played < times) {            
            audio.play();
        } else if (ended) {
            ended();
        }
    });
    audio.play();
}

var audio = document.getElementsByTagName("audio")[0];
play(audio, 3, function() {
    var sound = new Audio("http://www.soundjay.com/button/button-1.mp3");
    play(sound, 2);
});
<audio src="http://www.soundjay.com/button/beep-01a.mp3"></audio>
like image 42
noob Avatar answered Feb 15 '26 22:02

noob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!