Skip to main content

Using the SoundPlayer

Playing sounds requires three steps:

  1. Load audio files to be played.
  2. Add the SoundPlayer node to the scene.
  3. Control the SoundPlayer node with the Play action.

Load audio files

In the GameOptions object, the sounds property is an array of audio files that the game will use. Similar to the way font and image assets are loaded, each sound needs a soundName to identify the sound and a url from where it can be fetched.

sounds: [
{
// public domain, adapted from https://commons.wikimedia.org/wiki/File:Car_Horn.wav
soundName: "carHorn",
url: "sounds/car-horn.mp3"
},
]

Add the SoundPlayer

Create a new SoundPlayer node and specify which sound it will play. Use the same soundName as it appeared in the sounds array in GameOptions. Add the SoundPlayer to the scene.

const carSound = new SoundPlayer({
soundName: "carHorn",
});
sceneOne.addChild(carSound);

Control the SoundPlayer

The Play action will play the sound.

carSound.run(
Action.play()
)

The example below will play a beeping car horn sound each time the "BEEP" button is pushed.

Loading...
Explore:
  • The SoundPlayer will play the sound concurrently in response to multiple Play actions. In this example, the audio file is bird sound. Press the "SING" button repeatedly, and you will hear multiple instances of the audio file played.