What is the most efficient way to switch music tracks?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AfterCadaver

My Problem

In my game where I play background music I sometimes switch tracks. My previous method for accomplishing this was through having two AudioStreamPlayers. I would set one to play and the other to stop.

For some reason though, when the music is set to switch sometimes (inconsistently) the sound abruptly cuts off all of a sudden. This may be as a result of the improper method of switching tracks.

Solutions, Anybody?

The other methods I can think of I’m not sure about implementing.

I want to know what is the best way to be able to switch music.

:bust_in_silhouette: Reply From: Zylann

Rule #1 about best ways: there is no best way.
In the present case, stopping or starting music will never start instantaneously, because large music files are streamed and played in an audio thread, which is separate from the game logic thread which runs at different rates.

If what you want is to litterally stop the first music and play the second without any form of transition and no gap, that would have to happen inside the audio thread by queueing the events somehow. I’m not sure if Godot works in this way. If that’s really what you need (generative music loops?), you may want to ask for a fix or feature maybe?

What you can more likely do is a form of cross-fade:
Animate the volume of your first player to ramp down, and at the same time, animate the volume of the second player to ramp up. This should attenuate any form of “gap” or “click” there would be between the two tracks.
Sometimes in games a variant of this is used where only the preceding track fades out, while the next track plays directly at full volume after the previous has faded about 50%. This mostly works well if your two tracks are two different musics.

You can perform those fades using AnnimationPlayer, Tween, or just code.

Maybe you could also consider playing your two nodes all at the same time, while having only one audible, the others having volume of zero. It consumes more CPU but is close to what I’ve seen in some games, where audio is also not compressed, or compressed in a way that doesnt affect timing (as long as you don’t have too many tracks)

:bust_in_silhouette: Reply From: LefflerHirthe

I don’t understand your problem very well. I have never encountered this problem before. It’s seem like dzwonki mp3