preloading many sounds (in array)?

xnaxna
edited September 14 in p5.js Library Questions

What's the correct way to preload a lot of samples? Instead of just one file like shown in this video: 11.1: Loading and Playing - p5.js Sound Tutorial

Answers

  • not like this:

    var key53;
    var key54;
    var key55;
    var key56;
    var key57;
    var key58;
    var key59;
    var key60;
    var key61;
    var key62;
    var key63;
    var key64;
    var key65;
    var key66;
    var key67;
    var key68;
    var key69;
    var key70;
    var key71;
    var key72;
    var key73;
    var key74;
    var key75;
    var key76;
    var key77;
    
    function preload() {
        for(var i=53; i<77; i++){
            "key"+i = loadSound("keys/"+i+".wav")
      }
    }
    
  • Look at array in the reference:

  • I know about arrays, but the issue is here "key"+i =

  • edited September 14 Answer ✓
    • In programming, everything starts by describing the problem to solve. :-B
    • In this particular problem, you need to load audio files from a subfolder called "keys/".
    • Let's create a const variable for it then: const FOLDER = 'keys/'.
    • All of those files have extension ".wav". Then another const for it: const EXT = '.wav'.
    • Seems like the 1st ".wav" file you wish to load is named "53.wav", is that right? :-/
    • If so, we've got ourselves another const. Let's call it: const INDEX_START = 53.
    • Following the same logic, last file to load is "77.wav", right?: const INDEX_END = 77.
    • Now let's calculate how many files to load then: const INDEX_TOTAL = 1 + INDEX_END - INDEX_START.
    • Finally, let's declare a variable for an Array which is about to hold all of those p5.SoundFile object references: :-bd const sounds = Array(INDEX_TOTAL).
    • Now we can define a preload() for all of those pre-defined information: \m/
    const FOLDER = 'keys/', EXT = '.wav',
          INDEX_START = 53, INDEX_END = 77,
          INDEX_TOTAL = 1 + INDEX_END - INDEX_START,
          sounds = Array(INDEX_TOTAL);
    
    function preload() {
      for (let i = 0; i < INDEX_TOTAL; ++i)
        sounds[i] = loadSound(FOLDER + (i + INDEX_START) + EXT);
    }
    
  • @GoToLoop that's amazing. Thanks for this detailed answer. In the for loop, what is the "let" doing?

Sign In or Register to comment.