Skip to main content

Sound Effects

Learn how to add sound effects and music to make your games more immersive and fun.

Loading Sounds

Load sounds using preload(), just like images:

let jumpSound;

function preload() {
jumpSound = loadSound('jump.mp3');
}

function setup() {
createCanvas(400, 400);
}

function draw() {
background(220);
text("Press SPACE to jump", 200, 200);
}

function keyPressed() {
if (key === ' ') {
jumpSound.play();
}
}

Breaking it down

  • loadSound('filename.mp3') - Loads an audio file
  • Store in a variable to use later
  • .play() - Plays the sound once
  • Works with MP3, WAV, and OGG file formats

Uploading Sound Files

In p5.js Web Editor:

  1. Click the > arrow next to "Sketch Files"
  2. Click "Upload file"
  3. Choose your sound file (.mp3, .wav, or .ogg)
  4. Reference it by filename: 'sound.mp3'

From URL:

function preload() {
jumpSound = loadSound('https://example.com/jump.mp3');
}

Multiple Sounds

Load and play different sound effects:

let jumpSound;
let coinSound;
let gameOverSound;

function preload() {
jumpSound = loadSound('jump.mp3');
coinSound = loadSound('coin.mp3');
gameOverSound = loadSound('gameover.mp3');
}

function keyPressed() {
if (key === ' ') {
jumpSound.play();
}
}

function collectCoin() {
coinSound.play();
score++;
}

function endGame() {
gameOverSound.play();
}

Breaking it down

  • Each sound needs its own variable
  • Call .play() when the event happens
  • Can play multiple sounds simultaneously
  • Each sound plays independently

Background Music

Loop music continuously in the background:

let bgMusic;

function preload() {
bgMusic = loadSound('music.mp3');
}

function setup() {
createCanvas(400, 400);

// Start playing and loop forever
bgMusic.loop();
}

Breaking it down

  • .loop() - Plays the sound repeatedly
  • Starts immediately when called
  • Continues until stopped
  • Perfect for background music

Controlling Volume

Adjust how loud sounds are:

let bgMusic;
let coinSound;

function preload() {
bgMusic = loadSound('music.mp3');
coinSound = loadSound('coin.mp3');
}

function setup() {
createCanvas(400, 400);

// Set volume (0.0 to 1.0)
bgMusic.setVolume(0.3); // Quiet background music
coinSound.setVolume(0.8); // Louder sound effect

bgMusic.loop();
}

Breaking it down

  • .setVolume(level) - Sets volume from 0.0 (silent) to 1.0 (full volume)
  • 0.5 is half volume
  • Call before or after playing
  • Background music usually quieter than effects

Stopping Sounds

Stop sounds that are playing:

let bgMusic;

function setup() {
createCanvas(400, 400);
bgMusic.loop();
}

function keyPressed() {
if (key === 'p') {
// Pause the music
bgMusic.pause();
}

if (key === 'r') {
// Resume from where it paused
bgMusic.play();
}

if (key === 's') {
// Stop and reset to beginning
bgMusic.stop();
}
}

Breaking it down

  • .pause() - Pauses playback, remembers position
  • .play() - Resumes from pause or starts from beginning
  • .stop() - Stops and resets to start
  • .isPlaying() - Returns true if currently playing

Checking if Sound is Playing

Avoid playing the same sound too frequently:

let bgMusic;

function keyPressed() {
if (key === 'm') {
// Only start music if not already playing
if (!bgMusic.isPlaying()) {
bgMusic.loop();
}
}
}

Breaking it down

  • .isPlaying() - Returns true/false
  • Prevents overlapping the same sound
  • Useful for toggle buttons

Sound Playback Speed

Change pitch by adjusting playback speed:

let sound;

function preload() {
sound = loadSound('beep.mp3');
}

function keyPressed() {
if (key === '1') {
sound.rate(0.5); // Slower, lower pitch
sound.play();
}
if (key === '2') {
sound.rate(1.0); // Normal speed
sound.play();
}
if (key === '3') {
sound.rate(2.0); // Faster, higher pitch
sound.play();
}
}

Breaking it down

  • .rate(speed) - Changes playback speed
  • 1.0 is normal speed
  • Less than 1.0 is slower/lower pitch
  • Greater than 1.0 is faster/higher pitch

Pan (Left/Right Speaker)

Control which speaker plays the sound:

let sound;

function preload() {
sound = loadSound('effect.mp3');
}

function keyPressed() {
if (key === 'l') {
sound.pan(-1); // Left speaker only
sound.play();
}
if (key === 'c') {
sound.pan(0); // Center (both speakers)
sound.play();
}
if (key === 'r') {
sound.pan(1); // Right speaker only
sound.play();
}
}

Breaking it down

  • .pan(position) - Sets left/right balance
  • -1 is full left
  • 0 is center (both speakers)
  • 1 is full right
  • Creates spatial audio effects

Common Patterns

Jump Sound Effect

let jumpSound;
let isJumping = false;
let y = 300;

function preload() {
jumpSound = loadSound('jump.mp3');
}

function draw() {
background(220);
circle(200, y, 50);

if (isJumping) {
y = y - 5;
if (y <= 100) {
isJumping = false;
}
} else {
if (y < 300) {
y = y + 5;
}
}
}

function keyPressed() {
if (key === ' ' && y >= 300) {
jumpSound.play();
isJumping = true;
}
}

Collect Coin Sound

let coinSound;
let coins = [];
let score = 0;

function preload() {
coinSound = loadSound('coin.mp3');
}

function setup() {
createCanvas(400, 400);
// Create coins
for (let i = 0; i < 5; i++) {
coins.push({
x: random(50, 350),
y: random(50, 350)
});
}
}

function draw() {
background(220);

// Draw coins
fill(255, 215, 0);
for (let coin of coins) {
circle(coin.x, coin.y, 30);
}

// Check collision with player
for (let i = coins.length - 1; i >= 0; i--) {
let d = dist(mouseX, mouseY, coins[i].x, coins[i].y);
if (d < 30) {
coinSound.play();
coins.splice(i, 1);
score++;
}
}

text("Score: " + score, 20, 30);
}

Music Fade In

let bgMusic;
let volume = 0;

function preload() {
bgMusic = loadSound('music.mp3');
}

function setup() {
createCanvas(400, 400);
bgMusic.setVolume(0);
bgMusic.loop();
}

function draw() {
background(220);

// Gradually increase volume
if (volume < 0.5) {
volume = volume + 0.01;
bgMusic.setVolume(volume);
}
}

Toggle Mute

let bgMusic;
let isMuted = false;

function preload() {
bgMusic = loadSound('music.mp3');
}

function setup() {
createCanvas(400, 400);
bgMusic.loop();
}

function draw() {
background(220);

fill(0);
text(isMuted ? "MUTED" : "SOUND ON", 20, 20);
text("Press M to toggle", 20, 40);
}

function keyPressed() {
if (key === 'm') {
isMuted = !isMuted;

if (isMuted) {
bgMusic.setVolume(0);
} else {
bgMusic.setVolume(0.5);
}
}
}

Tips & Tricks

  1. Use preload() - Always load sounds in preload(), not setup()
  2. Lower music volume - Background music should be quieter than effects (0.2-0.4)
  3. Short sound files - Keep effects under 2 seconds
  4. File formats - MP3 works everywhere, WAV for higher quality
  5. Test on mute - Games should work without sound
  6. Mute button - Always give players a way to mute

Common Gotchas

⚠️ Sound not playing? - Check filename and that file is uploaded
⚠️ Too loud? - Use .setVolume() to lower it (try 0.3)
⚠️ Sound cuts off? - You might be calling .play() too often
⚠️ No autoplay? - Most browsers block autoplay; require user interaction first
⚠️ Clicking sounds? - Use .loop() for music, not repeated .play()

Sound File Formats

FormatProsConsUse For
MP3Small file size, universalLossy compressionMusic, long sounds
WAVHigh quality, no compressionLarge file sizeShort effects
OGGGood quality, small sizeLimited browser supportAlternative to MP3

Finding Free Sound Effects

Great websites for free game sounds:

  • Freesound.org - Huge library, needs account
  • OpenGameArt.org - Game-focused sounds
  • Kenney.nl - High quality sound packs
  • Zapsplat.com - Large collection, free

Audio Creation Tools

Make your own sounds:

  • BFXR - Classic 8-bit game sounds (free, web-based)
  • ChipTone - Retro game sound generator (free, web-based)
  • Audacity - Record and edit audio (free, download)
  • GarageBand - Music creation (free on Mac)

Try It Yourself

Experiment with these ideas:

  • Add jump and land sound effects to a platformer
  • Create a coin collection sound with score counter
  • Make background music that speeds up as you progress
  • Add different sounds for winning and losing
  • Create a rhythm game that responds to key presses

Ready to display text in your games? Check out the Text & Fonts guide! ✏️