Play .mp3s in Sequence with onended()?

Hi all, Continuing n00b adventures with p5.sound here. I'm trying to create a shuffle player in the browser. This code preloads a list of .mp3s called 1.mp3, 2.mp3, etc., up to 5.mp3, and then plays one file chosen with random() on mousePressed().

My questions: how to trigger each randomly selected file from the end of the previous file? How to loop this process, so that one randomly chosen file plays from the end of the previous one, on and on?

I suspect onended() will help. This thread addresses the use of onended() to trigger messages. I appreciate any clues you can provide! Thanks.

//Create array of .mp3s numbered 1 to 5.
const FOLDER = '1to5/', EXT = '.mp3',
      INDEX_START = 1, INDEX_END = 5,
      INDEX_TOTAL = 1 + INDEX_END - INDEX_START,
      sounds = Array(INDEX_TOTAL);

//Preload those files.
function preload() {
  for (let i = 0; i < INDEX_TOTAL; ++i) {
    sounds[i] = loadSound(FOLDER + (i + INDEX_START) + EXT);
    print("i = " + i);
  }

}

function setup() {
  createCanvas(200, 200);
  textAlign(CENTER);
  fill(100);
  noStroke();
  text("CLICK TO PLAY", width/2, height/2);
}

//Play one randomly chosen file.
function mousePressed() {
    var j = int(random(5));
    print("j = " + j);
    sounds[j].play();
}

Answers

  • edited May 2018 Answer ✓

    Perhaps something like this? NOT TESTED! Just a template:

    int idx = 0;
    
    function setup() {
      shuffle(sounds, true);
      for (const s of sounds)  s.onended(playNext);
    }
    
    function mousePressed() {
      sounds[idx].rewind().play();
    }
    
    function playNext() {
      console.log(`Finished sound index ${idx}: ${this.src}.`);
      this.rewind();
      sounds[idx = (idx + 1) % sounds.length].play();
    }
    
  • This is a great start! Thank you @GoToLoop !

  • hey @gotoloop ! thanks again for the help--this solved a problem I've been struggling with for weeks. I took out this.rewind(); and your code works like a charm.

Sign In or Register to comment.