Title is a mouthful, right? But this is something I’ve been trying and failing to find a clear answer to for months. Now that I’ve found the answer, time to take Sal‘s advice and write a blog post.
The Basic Idea
You’re making a video game. You’re using Godot because you like open source and free stuff. You’ve got some kick-awesome background music because, well, reasons. And while you can get a good loop out of the music, you’d still like to have an introduction to the music.
Background music with an intro is pretty standard in most video game music. Take a listen to “Green Hill Zone” from… well, every Sonic game ever. But particularly Sonic Mania.
Notice how when the music loops at 0:53, it doesn’t go all the way back to the beginning but instead loops from partway into the music? This helps set the stage for the level’s atmosphere and provide a more natural feel to the music.
It’s also a feature we’ve come to expect as players, so if you can do it in your game it’s a good idea. So how do we get it in Godot?
Preparing Your Music
For my game, I’m using “1977” by Adam Young as the background music. I will, of course, need to replace it with something officially licensed (or original) for the finished product. I used my copy of Ableton Live to process the audio in order to get a clean-ish loop and saved it as an Ogg Vorbis file to be imported into Godot.
Import into Godot
The key info for the loop is kept on the file itself. We want the file to loop (obviously), and we want to set the loop offset at where we want the looping portion of the file to begin. This value is in seconds!
Now for the unintuitive part: do not auto-play the music.
Selecting Autoplay here will start playback at the loop offset, which will skip the intro. That’s the exact thing we’re trying to avoid!
Instead of autoplaying, we need to add a line to the root node’s script:
What’s the difference? We’re using the
play method in the AudioStreamPlayer class. This method uses an optional parameter to indicate where to start playing from. We want to start playing from the beginning, so we pass
0 to the method.
The end result should be background audio that starts playing at the beginning of the file but loops over only one specific part of it.
Hope this helps! Leave a comment if you’ve got feedback.