Phaser: Playing sounds
This post is part of a Phaser series. Click here to see the first post of the series.
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 into 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.
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X