preload()
preload() runs before setup() and is where p5.js loads external resources like images, fonts, and sounds. Starting audio generators here ensures they're ready the moment a jump or collision happens.
function preload() {
// Load sound effects
// Using p5.Noise for simple sounds, but you could load .wav or .mp3 files
jumpSound = new p5.Noise('white'); // 'white', 'pink', 'brown'
jumpSound.amp(0); // Start silent
jumpSound.start();
gameOverSound = new p5.Noise('brown');
gameOverSound.amp(0); // Start silent
gameOverSound.start();
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
jumpSound = new p5.Noise('white');
Creates a white noise oscillator for the jump sound effect
gameOverSound = new p5.Noise('brown');
Creates a brown noise oscillator for the game over sound effect
jumpSound = new p5.Noise('white');- Creates a white noise generator—this is the raw sound object we'll trigger when jumping. 'white' noise contains all frequencies at equal volume
jumpSound.amp(0);- Sets the initial amplitude (volume) to 0 so the sound is silent until we explicitly play it
jumpSound.start();- Starts the noise generator running in the background; it's silent but ready to become audible instantly when we need it
gameOverSound = new p5.Noise('brown');- Creates a brown noise generator for the game over sound—'brown' noise has more bass frequencies than white noise
gameOverSound.amp(0);- Keeps the game over sound silent until the collision happens
gameOverSound.start();- Starts the game over sound generator running in the background