Persistent background music

beginner

By: Henrique Campos - July 15, 2020

Background music is one of the most immersive elements of a game. It dictates the mood and pace of a level or even of the whole play through, but there’s a common mistake that may happen when we are working with background music in most game engines. When transitioning between game scenes the music gets cut and is common that it restart from beginning, completely breaking the immersion.

One of the simplest ways we can solve this problem is by using a Singleton responsible to play the background music. Since singletons are accessible globally and there can only be a single instance of them, they can be used to maintain the music playing while all other objects are freed from memory between scene transitions.

The BackgroundMusic Singleton

In Godot Engine we can play audio stream files through an AudioStreamPlayer Node. We are going to use it and rename it as BackgroundMusic, alternatively you can already drag your music file to the Stream property slot and toggle on the Autoplay flag.

BackgroundMusic settings

With that we just need to turn this scene into an Autoload. In Godot Engine an Autoload is a scene that is loaded automatically and instanced aside from the main scene, allowing it to be apart from changes in the SceneTree structure caused by the get_tree().change_scene and get_tree().change_scene_to methods. In other words, when calling one of those methods an Autoload stays in the SceneTree processing normally.

Let’s turn our BackgroundMusic into an Autoload now. In the Project > Project Settings > Autoload browse the BackgroundMusic file to set it as an Autoload.

Enabling the BackgroundMusic as an Autoload

Now whenever you test your game the BackgroundMusic will instance alongside the scene you are testing and won’t be removed unless you manually queue_free it and with that our BackgroundMusic can keep playing throughout scenes.

Made by

Our tutorials are the result of careful teamwork to ensure we produce high quality content. The following team members worked on this one:

Henrique Campos

Tutor

Nathan Lovato

Founder

Related courses

Banner image

Ultimate Godot course bundle 235$

This ultimate bundle gives you access to ALL our current and future Godot courses, at a discount. It’s like a lifetime membership.

Banner image

Godot secrets bundle 150$

A bundle with our four secrets courses at the price of three! It contains 2D Secrets, Shader Secrets, VFX Secrets, and PCG Secrets.

Related tutorials

No questions yet

Got a question or feedback regarding this guide?
Please use the form below.

Enter your email to get notified when someone replies to your comment.
We encrypt your addres with a strong 256-bit AES encryption.
We'll only use your address for notifications. You can unsubscribe anytime.