Phaser: Playing sounds

By

Learn how to play sounds in Phaser by preloading an audio file with this.load.audio, adding it with this.sound.add, and calling play when you need it.

~~~

This post is part of a Phaser series. Click here to see the first post of the series.

Playing a sound in Phaser takes three steps: preload the audio file, add it to the sound manager, and call play() when you need it. Let’s see each step.

Similar to displaying images, before you can play an audio file, you must preload it and assign it to a label:

function preload() {
  this.load.audio('sound', 'sound.mp3')
}

For images we used this.load.image(), here we use this.load.audio().

Once this is done, we can use the sound in our create() or update() functions:

this.sound.add('sound')

This will get you back an object. It’s important to assign it to a variable:

const sound = this.sound.add('sound')

Because later, when we want, we’ll call the play() method on it:

sound.play()

You can combine this with mouse events, for example, to play a sound when an item is clicked or hovered.

Loading multiple formats

Not every browser plays every audio format. You can pass an array of files, and Phaser picks the first one the browser can play:

function preload() {
  this.load.audio('jump', ['jump.ogg', 'jump.mp3'])
}

Both files contain the same sound, just encoded differently.

Volume and looping

You can pass a configuration object when you add the sound. This is handy for background music, which you want quieter and looping forever:

const music = this.sound.add('music', { loop: true, volume: 0.2 })
music.play()

Volume goes from 0 to 1. To stop the sound, call music.stop().

You can also pass the same kind of config to play() itself:

sound.play({ volume: 0.5 })

Why doesn’t my sound play?

Here’s a pitfall that gets everyone at least once. Browsers block audio until the user interacts with the page. It’s the autoplay policy.

If you call play() inside create(), right when the game loads, you might hear nothing. Phaser unlocks the audio as soon as the user clicks or taps, but sounds triggered before that moment are blocked.

The fix is to start sounds from an input event:

this.input.on('pointerdown', () => {
  music.play()
})

Sound effects tied to gameplay, like a jump triggered by a key press, don’t have this problem. The user already interacted with the page by then.

Tagged: Phaser · All topics
~~~

Related posts about phaser: