'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.



Solution 1:[1]

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

Solution 2:[2]

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>

Solution 3:[3]

a dirty solution that does work for this problem is to set an interval:

var sound = new Audio(document.getElementById("audio").src)
var trackLength = 5000 // 5 seconds for instance
var playthroughs = 3 //play through the file 3 times

var player = setInterval(function(){
    if(playthroughs > 0){
        sound.play();
        playthroughs--;
    }
    else clearInterval(player)
}, trackLength);

EDIT: After someone pointed out to me my code could use a little improvement, i kinda got carried away a little. Here's the result:

var Sound = {
  que: {
    items: [],

    add: function(name){
      if(Sound.lib.items[name]) return Sound.que.items.push(Sound.lib.items[name]) - 1;
    },

    remove: function(key){
      Sound.que.items.splice(key, 1);
    },

    clear: function(){
      Sound.que.items = [];
    },

    play: function(startTrack){
      var playing = startTrack -1 || 0;


      var playNext = function(key){
        if(Sound.que.items[key]){
          if(Sound.que.items[key].isLoaded){
            var trackLength = Math.floor(Sound.que.items[playing].duration * 1000);

            Sound.que.items[key].play();

            var play = setTimeout(function(){
              playing++
              playNext(key +1)
            }, trackLength)
          }
          else{
            Sound.que.items[key].addEventListener('canplaythrough', function(){
              playNext(key);
          })
        }

        }
      }

      playNext(playing);
    }
  },
  lib: {
    items: {},

    add: function(src, name){
      var obj = new Audio(src);
          obj.addEventListener('canplaythrough', function(){
            this.isLoaded = true;
          })
      if(!name){
        var key = 0;
        for(i in Sound.lib.items){
          key++;
        }
        name = key;
      }

      Sound.lib.items[name] = obj;
    },

    remove: function(name){
      if(typeof name == "string"){
        delete Sound.lib.items[name];
      }
    }
  },
}

an object oriented approach to this. it has a simple library of sounds and a que to which the sounds can be added in any order. i dont know if its fully debugged, but it seems to work nicely.

To add a new audio file to the library:

Sound.lib.add('path/to/file.mp3', 'trackName'); //trackname will be numerical if none is given.

To add an audio file to the que:

Sound.que.add('trackName');

To play the que:

Sound.que.play(2); // 2 indicates to start playing at the second sound in the que, assuming the que has 2 or more sounds in it.

To clear the que:

Sound.que.clear()

There's some more functionality in there, like clearing the que, removing items from the que and/or library. But it shouldnt be all that hard to figure out.

Solution 4:[4]

The only way to do this is using Web Audio API (spec) MDN page. This is however a standard that is in development, and therefore not finalised.

Solution 5:[5]

Not exactly a direct answer to the question, but to play an HTML5 audio indefinitely you can do as follow:

const audio = new Audio('url_here.mp3');
audio.loop = true;
audio.play();

Solution 6:[6]

I think the most seamless way to do it is in Javascript

var sound=new Audio(document.getElementById("audio").src);
for(var i=0;i<3;i++){
   sound.play();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ??????? ???????
Solution 2 noob
Solution 3
Solution 4 Jon Koops
Solution 5 Danny Coulombe
Solution 6 scrblnrd3