preload()
preload() is called automatically by p5.js before setup(). It's the perfect place to load images, sounds, and other files from the internet that your sketch needs. Without preload(), your sketch might try to draw before the files finish downloading.
function preload() {
// Load the sound file here. This function runs before setup() and draw().
// Using a CORS-friendly preview URL from freesound.org
// Source: https://freesound.org/s/235970/ (Drum Beat, 100 bpm)
throwSound = loadSound('https://freesound.org/data/previews/235/235970_42065-lq.ogg');
}
Line-by-line explanation (2 lines)
🔧 Subcomponents:
throwSound = loadSound('https://freesound.org/data/previews/235/235970_42065-lq.ogg');
Fetches the drum sound from the internet and stores it in a variable so it can be played later
function preload() {- preload() is a special p5.js function that runs once, before setup() and draw(), giving you time to load files from the internet
throwSound = loadSound('https://freesound.org/data/previews/235/235970_42065-lq.ogg');- loadSound() downloads the audio file from the URL and stores it in the throwSound variable—this is why preload() is needed, so the sketch waits for the file to arrive before continuing