Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Audio and UI

Audio Basics

Play sound effects and music in Phaser. Learn the sound manager, pitch and volume control, audio sprites, mute and the browser autoplay lock.

Sound turns a moving picture into a game. A coin that goes "ting", a jump that goes "whoop" and a looping background track change how a game feels more than almost any visual effect. Phaser has a sound manager that loads audio files, plays several sounds at once, controls volume and pitch, and deals with the differences between browsers.

The lesson has two practical limits to know about. First, browsers refuse to play sound until the user has interacted with the page, so every game must cope with a locked audio system. Second, the sandbox on this site cannot load audio files from your own server. So the runnable examples create their sounds with the Web Audio API inside the page and hand them to Phaser's sound cache. In a real game you replace that small helper with this.load.audio(...) and the rest of the code does not change.

Loading audio files

In a normal project you load audio in preload(). Provide the same sound in more than one format, because not every browser supports every codec:

JavaScript
preload() {
  this.load.audio('coin', ['assets/coin.ogg', 'assets/coin.mp3']);
  this.load.audio('music', ['assets/theme.ogg', 'assets/theme.mp3']);
}

Phaser picks the first format the browser can play. MP3 and AAC work everywhere today, OGG is smaller for the same quality in browsers that support it, and WAV is large and best kept for tiny effects. Keep music files compressed, since a three-minute WAV can be 30 MB.

Playing sounds

There are two ways to play a sound:

JavaScript
// one-shot: fire and forget (good for effects)
this.sound.play('coin', { volume: 0.6 });

// a sound object you keep (good for music and anything you control later)
const music = this.sound.add('music', { loop: true, volume: 0.4 });
music.play();

this.sound.play creates a temporary sound that is removed when it finishes. this.sound.add returns a Sound object that you can pause, resume, stop, change and reuse. The play configuration takes these fields:

Field Meaning
volume 0 (silent) to 1 (full)
loop Repeat forever when true
rate Playback speed; 1 is normal, 2 is double speed and one octave higher
detune Pitch change in cents (100 cents is one semitone)
seek Start position in seconds
delay Wait before starting, in seconds
pan Stereo position from -1 (left) to 1 (right) (Web Audio only)

Useful methods on a sound: pause(), resume(), stop(), setVolume(v), setRate(r), setDetune(d), setLoop(true). Useful properties: isPlaying, isPaused, duration, seek. Useful events: complete (finished), looped, play, pause, stop.

The sound manager has global controls as well: this.sound.volume, this.sound.mute, this.sound.pauseAll(), resumeAll() and stopAll(). A settings screen is mostly a pair of sliders for music and effects, plus a mute toggle.

The autoplay lock

Browsers block audio until the user has clicked, tapped or pressed a key on the page. Phaser knows this: it creates the audio context in a locked state and unlocks it on the first input. If you call play() while the sound manager is still locked, Phaser waits and plays the sound as soon as the unlock happens, so a music track started in create() often begins right after the player's first click.

You can check and react to this:

JavaScript
if (this.sound.locked) {
  this.sound.once(Phaser.Sound.Events.UNLOCKED, () => music.play());
} else {
  music.play();
}

A friendly pattern is a "Click to start" title screen: the click unlocks audio, and the music starts on the menu. Never rely on sound playing in create() of the very first scene without any interaction.

flowchart LR
  A["Page loads"] --> B{"First click,<br/>tap or key?"}
  B -- no --> C["Audio context locked<br/>(play requests wait)"]
  B -- yes --> D["Phaser unlocks audio"]
  C --> B
  D --> E["Queued and new sounds play"]

Phaser holds play requests until the browser allows sound.

Sound effects with pitch variation

A sound heard fifty times gets boring. Changing the pitch a little each time makes repeated effects (footsteps, coin pickups, hits) feel natural, and it costs nothing. The detune option is perfect for this.

Sound pad with pitch and volume

The first click on a pad unlocks audio and plays that note. Press the pads repeatedly and listen: the small random detune makes the same sound a little different every time. this.sound.mute silences everything without stopping the sounds, so unmuting resumes them.

Music that you control

Music is a long, looping Sound object that you keep. The usual needs are: start it once, not once per scene restart; fade it in and out; lower it during dialogue; stop it when the game ends. Because a Sound has a volume property, you can fade it with a tween like any other number.

Looping music with fades

The green bar shows the music volume while the tween runs. A very common mistake is to call this.sound.add('music').play() in the create() of a scene that restarts; every restart then starts another copy of the music on top of the others. Create the music object once (in a boot scene, or guard with if (!this.sound.get('music'))) and keep reusing it.

Audio sprites

When a game has dozens of short effects, loading each as a separate file is slow. An audio sprite packs many effects into one file plus a JSON file that says where each effect starts and ends. You load it once with this.load.audioSprite('sfx', 'sfx.json', ['sfx.ogg', 'sfx.mp3']) and play a named part:

JavaScript
this.sound.playAudioSprite('sfx', 'explosion');

Tools such as audiosprite generate the files. The benefit is fewer network requests, and the sprite plays in all supported browsers.

Practical rules

  • Respect the player. Offer volume sliders and a mute toggle, and remember the choice (see Events, Registry and Saving).
  • Pause on blur. By default Phaser pauses sound when the tab loses focus (pauseOnBlur). Keep that: a hidden game should not keep playing.
  • Layer effects. Several sounds play at once without trouble, but spam can clip. Limit the same sound to a few instances, or check isPlaying first.
  • Mobile. iOS and Android only unlock audio after a real touch, and some devices have no stereo or limited channels. Test on a phone.
  • Disabling audio. Set audio: { noAudio: true } in the game config to turn the whole system off, useful in automated tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do games often start their music after the first click?

    Autoplay policies keep audio locked until a user gesture. Phaser waits for the unlock and plays queued sounds afterward.
  2. 2. Which call gives you a Sound object that you can pause and fade later?

    sound.add returns a reusable Sound object. sound.play is for one-shot effects whose temporary sound is removed when finished.
  3. 3. How can you make a repeated coin sound feel less repetitive?

    Slight random pitch variation makes the same sample sound different each time, at no cost.
  4. 4. A scene that restarts calls this.sound.add('music').play() in create(). What problem appears?

    Each add creates another Sound object. Create the music once or look it up with this.sound.get before adding.

Summary

  • Load audio in several formats with load.audio; play one-shots with sound.play and keep controllable sounds with sound.add.
  • Configure volume, loop, rate, detune, seek, delay and pan; control all sound with sound.volume, sound.mute, pauseAll and stopAll.
  • Browsers lock audio until the first interaction; Phaser queues plays and exposes sound.locked and the unlocked event.
  • Fade music by tweening its volume, and avoid creating duplicate music objects.
  • Audio sprites pack many effects into one file; vary pitch to avoid repetition.

Next: Text and Buttons