List all sounds from a Scene

Hi,

I am using sounds in my scene, like

// Scene A
var sound1 = this.sound.add('explo');
var sound2 = this.sound.add('win');

Also, another scene with more sounds (some are the same keys):

// Scene B
var sound1 = this.sound.add('reload');
var sound2 = this.sound.add('explo');

Now, those scenes are visible at the same time. I need to close SceneB, and before doing so, I need to stop all sounds still playing. But if using:

this.game.sound.stopAll();

it stops even the sounds from SceneA. Is there a way to find which sounds belong in a scene?

UPDATE: how do sounds are played? When stopping a sound (key “explo”), if both scene play the sound at the same time, calling sound2.stop() will results in stopping sounds from all scenes. Each scene doesn’t seem to have its own instance of a sound?

Thanks!

1 Like

No, you would need to store the created sounds on the scene to stop them later.

Just to follow-up on my post, after doing some deeper research, I saw that each sound loaded is not directly mapped to a specific scene. In addition, playing a sound always plays the same instance, so if SceneA plays sound ‘explo’, then SceneB plays it as well, it actually plays the same sound instance. There are not different instances per scene.

My solution is: for each scene in my example, I load the same sound file (like explo.mp3) with different keynames for each scene (like ‘A_explo’ and ‘B_explo’). Then, to stop ongoing sounds from SceneA, I loop:

for (var i = 0; i < this.game.sound.sounds.length; i++) {
  if (this.game.sound.sounds[i].key.slice(0, 2) == "A_") {
    this.game.sound.sounds[i].stop();
  }
}

I believe Phaser has the ability to support multiple instances for a sound, but I didn’t go deeper in that. Hope this helps anyone.

Audio sources in Phaser’s cache are shared, but every Sound is a unique object — created by sound.play(…) or sound.add(…) and stored in the global Sound Manager.