preload()
preload() runs once before setup() and is designed for loading resources like images, sounds, and fonts. With p5.sound, oscillators must be created and started in preload() (or setup()), then controlled later by fading their amplitude in and out. The three different waveforms (sine, triangle, square) produce different timbres: sine is smooth, triangle is mellow, and square is buzzy.
🔬 These three lines create the shoot sound. Try changing the frequency from 440 to 220 (twice as low) or 880 (twice as high)—what pitch do you hear when you shoot?
shootSound = new p5.Oscillator();
shootSound.setType('sine');
shootSound.freq(440); // A4
shootSound.amp(0);
shootSound.start();
function preload() {
// Create simple procedural sounds using p5.Sound
// Shoot sound: short, sharp tone
shootSound = new p5.Oscillator();
shootSound.setType('sine');
shootSound.freq(440); // A4
shootSound.amp(0);
shootSound.start(); // Start oscillator, but keep amplitude at 0
// Hit sound: short, high-pitched tone
hitSound = new p5.Oscillator();
hitSound.setType('triangle');
hitSound.freq(880); // A5
hitSound.amp(0);
hitSound.start(); // Start oscillator, but keep amplitude at 0
// Game Over sound: lower, sustained tone
gameOverSound = new p5.Oscillator();
gameOverSound.setType('square');
gameOverSound.freq(220); // A3
gameOverSound.amp(0);
gameOverSound.start(); // Start oscillator, but keep amplitude at 0
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
shootSound = new p5.Oscillator(); shootSound.setType('sine'); shootSound.freq(440); shootSound.amp(0); shootSound.start();
Creates a sine-wave oscillator at 440 Hz (musical note A4) that starts silently and is ready to fade in when the player shoots
hitSound = new p5.Oscillator(); hitSound.setType('triangle'); hitSound.freq(880); hitSound.amp(0); hitSound.start();
Creates a triangle-wave oscillator at 880 Hz (A5, one octave higher) for a high-pitched collision feedback sound
gameOverSound = new p5.Oscillator(); gameOverSound.setType('square'); gameOverSound.freq(220); gameOverSound.amp(0); gameOverSound.start();
Creates a square-wave oscillator at 220 Hz (A3, one octave lower) for a deep game-over tone
shootSound = new p5.Oscillator();- Creates a new oscillator object—this generates sound waves that will play when triggered
shootSound.setType('sine');- Sets the oscillator to produce a smooth sine wave; other options are 'triangle', 'square', or 'sawtooth' for different timbres
shootSound.freq(440); // A4- Sets the frequency to 440 Hz, which is the musical note A4 (the standard tuning reference in music)
shootSound.amp(0);- Sets amplitude to 0, meaning the sound is currently silent; this is required before calling start()
shootSound.start(); // Start oscillator, but keep amplitude at 0- Starts the oscillator running in the background—it remains inaudible until we fade its amplitude in later