Looping through audio files

Hi there,

I am currently working on the drum machine project in React. I have a minimum viable product working but I want to push things further.

I have a record button on my project which record the button pressed and stores the sounds in an array in the state of my app. I want to create a loop by playing the sounds in the array on repeat.

I tried something like this:

let audio = new Audio();
        var playlist = this.state.sequence; // load the sequence of sounds
        audio.src = playlist[0].src; // set the source of the first file in my array
        audio.play(); 
        // when the song ends, load the new sound
        audio.addEventListener('ended', function(){
            // increment playlist[i].src
        }, true);
        audio.loop = false;

However, I don’t know if it’s the right way to do so… Is there a way to achieve such thing ?

hey,
yes you can use setInterval() function for this kind of thing and have it play a sound every second or however long you thinks best, you can have it repeat by putting an if statement at the bottom with something like if(i == playlist.length) i = 0;
hope this helps. :slightly_smiling_face:

If each sound is a different length, this suggestion could be problematic. Ideally, you want to only play the next sound when the previous sound has played in its entirety.

2 Likes

The following is a very crude sequential sound file player.

const playSequence = (sounds) => {
  const playNextSound = () => {
    audio.src = sounds[currentSoundIndex++];
    audio.currentTime = 0;
    audio.play();
  };

  let currentSoundIndex = 0;
  if (sounds.length) {  
    const audio = new Audio();
    playNextSound();

    audio.addEventListener('ended', () => {
      if (currentSoundIndex < sounds.length) {
        playNextSound();
      }
    });
  }
}

playSequence(['path-to-file.mp3', 'path-to-file.mp3', 'path-to-file.mp3']);

Thanks for the replies. I will try the solution you suggested. :smile:

I actually found an alternative using recursive code:


let sounds = [...this.state.sequence];
        const playNextSounds = (sounds) => {
            if(sounds.length > 0){
                const audio = new Audio();
                console.log(sounds);
                audio.src = sounds[0].src;
                audio.currentTime = 0;
                audio.play();
                sounds.shift();
                audio.addEventListener('ended', function(){
                    return playNextSounds(sounds);
                })
            }