Sound and music
Sounds belong to a sprite or stage and play once: a jump, a coin, a door. Music belongs to the window: one track at a time, on a loop, and it keeps playing when the stage changes.
Sounds
Add a sound first, then play it by name. Click the stage, then press space:
| Scratch | Java |
|---|---|
| start sound [handleCoins v] | playSound("handleCoins") |
| stop all sounds | stopAllSounds() |
| set volume to (50) % | setVolume(50) |
| change volume by (-10) | changeVolume(-10) |
playSound does nothing while the same sound is still playing. For a sound that
may overlap itself, like quick shots, use playSoundCopy("laser", 100), where 100 is the volume.
There are 266 built-in sounds. Press play on that page to listen. Your own files work too, with a name:
this.addSound("jump", "assets/jump.wav");
Music
playMusic plays a track on a loop until you stop it. Asking for the track that
is already playing does nothing, so every stage can ask for its music in its
constructor. Press 1, 2 and S:
For a real game, use your own music file: playMusic("assets/theme.ogg").
- Prefer Ogg to WAV. A WAV file is as large in memory as on disk.
- An Ogg file longer than 20 seconds is streamed: it is read a little at a time while it plays, so a long song does not fill the memory.
- Free music: OpenGameArt, Free Music Archive. Edit sounds with Audacity.
Volume for the player
Players expect two sliders in the options: music and sounds. Both go from 0 to 100:
Window window = Window.getInstance();
window.setMusicVolume(40); // the music
window.setSoundVolume(80); // every sound, on top of each sprite's own volume
Menus shows how to make the sliders.
Next
- Built-in sounds
- Volume example
- Window.playMusic in the reference