How to play music across multiple scenes (2D)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Vista1337
:warning: Old Version Published before Godot 3 was released.

Hey, so I’m working on a simple 2D quiz game, and I’ve set it up with multiple scenes, you go from the main menu scene, to the question category scene and then you’re taken to the quiz scene.

So I’d like to play a global song that automatically plays when you launch the game and as you play through it.

One method that I have right now is I’ve set up a SamplePlayer and I’ve attached it to the main menu scene. It works, but when I change scenes, it stops playing and is interrupted.
I’m assuming that if I set up the same SamplePlayer on the other scenes the music will also get interruped and start all over again, which I don’t want.

So TLDR; How do I set up a song to be played throughout multiple scenes without interruption? Thanks.

:bust_in_silhouette: Reply From: cardoso

I suppose you can create a scene that would be loaded globally everytime.
You would put the SamplePlayer / StreamPlayer there.

You can see the autoload logic here: Singletons (Autoload) — Godot Engine (stable) documentation in English

But the difference from that documentation to your case, is that you would not be creating a script only, but a scene (with a script if needed, I guess).

So, assuming your SamplePlayer node is named “samplePlayer”, and the global scene is named “global.tscn”, you could always access it from anywhere in the code as global.get_node("samplePlayer") .

Or if you attach a script to that global scene you could save the player in a variable, var samplePlayer = get_node("samplePlayer") and access it from outside asglobal.samplePlayer

But how would I play the sounds? Is global.get_node("samplePlayer") enough to get it to play the song? Don’t I have to use the play function?

Vista1337 | 2017-11-28 22:11

Yes, you still have to use the play() function.

You can add/attach a script to the global scene, and there you can use the play.
So if you want the music to start immediately playing you can do it in the _ready function in script:

_ready():
   get_node("samplePlayer").play()

Or even more simple, on the scene editor panel, if you select the samplePlayer node there should be an autoplay option.

cardoso | 2017-11-28 22:27