How to stop a song in Phaser 3

I need to be able to stop all sound when I move from one scene to another. I am using WebAudio. I call a song like this: this.level1Song.play(); Looking at the documentation, I should be able to stop it like this: this.level1Song.stopAll(); I get this error when I do: Uncaught TypeError: Cannot read property ‘stopAll’ of undefined. Once I can stop a song, I plan on calling it in the change of scene areas on the game. Thanks for your help!

It sounds like you’re out of scope when calling this.level1Song.stopAll();. You’d need to post your complete code, or better yet set up a CodePen/JSFiddle.

function preload()
{
// Load audio assets
this.load.audio(‘worldmusic’, ‘assets/audio/bg-music.mp3’);
}

function create()
{
// Add a background music to the game on a loop
music = this.sound.add(‘worldmusic’);
}

function update ()
{
music.stop();
{

I was already calling it like this:
import- import level1SongMp3 from ‘…/assets/audio/level1Song.mp3’;

import level1SongOgg from ‘…/assets/audio/level1Song.ogg’;
in preload()
scene.load.audio(‘level1Song’, [
level1SongMp3,
level1SongOgg,
]);

in the constructor()
this.level1Song = scene.sound.add(key);
this.level1Song.play();
And it plays. I added the stop as suggested in the update as displayed below.
in update()
this.level1Song.stop();
I am getting this error: Uncaught TypeError: Cannot read property ‘stop’ of undefined. Does anyone have any ideas?

I added it to an update function like Manuel suggested and it has worked great since then

Hello @flurp

Is there any way you want to stop music? I mean when user clicked a button, when button reach some place or smt.

You can bind an event to a sprite and on callback you can do music.stop();

Maybe smt like this:

this.gl = this.sound.add('gl');
this.gl.play('', { delay: 3 });
var sp = this.add.sprite(250, 250, 'myButton')
    .setInteractive({ useHandCursor: true })
    .on('pointerdown', () => {
        this.gl.stop();
    }, this);

If you are not in scope of the music variable / reference, you can also do it this way:
Assuming this is the code when you load the music
this.load.audio(‘backgroundMusic’, ‘your path’);
You can stop by doing this from any scene
this.sound.get(‘backgroundMusic’).stop();