playSound()

Category:Game Lab

Plays the MP3 sound file from the specified URL.

Games play sounds to make them more engaging. You can add sounds to your games that are triggered by mouse or keyboard actions, or based on sprite collisions, or just based on other game code. There are two ways to fill in the url string for the first parameter.

1. Copy the URL of a sound on the web. In most browsers you can simply right-click (ctrl+click on a Mac) on a sound file and you'll see a menu with a few option. One will be to copy the URL of the sound. Note: We have listed some existing audio files that you can use in your game below.

2. Upload your own sound file to Game Lab. You can upload sound files saved on your computer to your game in Game Lab.

  • Click the pulldown arrow in the image URL field and then click "Choose..."
  • Then click the "Upload File" button the in the window.
  • Then choose the file from your computer by navigating to it
  • Once its uploaded click "Choose" next to it. This will insert the name of the file into the URL field. Because you have uploaded it, it doesn't need to be an HTTP reference.

Sample sounds

Sound URL
Start 1 https://audio.code.org/start1.mp3
Start 2 https://audio.code.org/start2.mp3
Goal 1 https://audio.code.org/goal1.mp3
Goal 2 https://audio.code.org/goal2.mp3
Win point 1 https://audio.code.org/winpoint1.mp3
Win point 2 https://audio.code.org/winpoint2.mp3
Lose point 1 https://audio.code.org/losepoint1.mp3
Lose point 2 https://audio.code.org/losepoint2.mp3
Win 1 https://audio.code.org/win1.mp3
Win 2 https://audio.code.org/win2.mp3
Win 3 https://audio.code.org/win3.mp3
Failure 1 https://audio.code.org/failure1.mp3
Failure 2 https://audio.code.org/failure2.mp3
Failure 3 https://audio.code.org/failure3.mp3

Examples

Making Music

Loop some background sounds.

// Loop some background sounds.
playSound("https://audio.code.org/win3.mp3", true);

playSound("https://audio.code.org/winpoint1.mp3", false);

Stay on the Screen

Play a failure sound whenever a sprite reaches the edge of the display area.

// Play a failure sound whenever a sprite reaches the edge of the display area.
var sprite = createSprite(200, 200);
sprite.setSpeedAndDirection(randomNumber(-5, -5), randomNumber(-180, 180));
function draw() {
  background("white");
  drawSprites();
  if (sprite.x<0 || sprite.x>400 || sprite.y<0 || sprite.y>400 ) {
    playSound("https://audio.code.org/failure1.mp3");
    sprite.setSpeedAndDirection(randomNumber(-5, -5), randomNumber(-180, 180));
  }
}

Syntax

playSound(url, loop)

Parameters

NameTypeRequired?Description
url String The source URL (or filename for an uploaded file) of the MP3 sound file to be played.
loop Boolean Should the sound file be played again and again (looped)? Default is false.

Returns

No return value. Plays a sound only.

Tips

  • The sound URL requires the full http:// prefix.

Found a bug in the documentation? Let us know at documentation@code.org