Godot 4 courses Launching in Early Access starting Jan 30
you can now pre-order
godot 4 courses
Save up to 25%

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

Learn 2D Gamedev with Godot 4 $99.95

Built on the success of GDQuest’s bestselling course, this Godot 4 course uses cutting edge ed-tech to teach the fundamentals of game development over 19 modules packed with interactive exercises.

Banner image

Learn 3D Gamedev with Godot 4 $99.95

This long-awaited course adds a third dimension to the knowledge you pick up in Learn 2D Gamedev. By the end of it, you will have the skills to build your own 3D game.

Related tutorials