Switching Stream of Autoloaded AudioPlayer?

Hi!

I’ve been trying to figure out a way to switch streams in the autoloaded audio_player/AudioPlayer2D node. My goal is to have dedicated menu music, while the music for the rest of the game plays consistently between levels. I’ve tried setting the default stream as my desired menu music, with this in the func _ready() of the first level scene:

var bgm = $/root/AudioPlayer/AudioStreamPlayer2D
bgm.stream = game_music
bgm.play()

with game_music being assigned to preload(“audio.mp3”) for the desired level music.
This allows me to switch tracks between the menu and the rest of the game, however, the track resets at the start of each level. How would I go about achieving a more seamless result?

Thanks in advance.

Hi,

since each level is loaded, when its ready method is called with your above code, it will set and play each time.

im having a rough play around with it, we could use the music autoloaded scene where we already have the music playing.

ok, bit of a dirty workaround.

what ive done, in the start_menu.gd and the level.gd scripts add this ready method

func _ready():
	AudioPlayer.level_changed()

ill create this function in the autoloaded script in a sec.

so in the audio_player.gd script, pop these at the top, if theyre not there already, just references to the two audio streams you want for level and start music

@onready var title_music = preload("res://assets/audio/title.wav")
@onready var level_music = preload("res://assets/audio/music.ogg")
@onready var music_player = $MusicPlayer

so now if you add this following function to the audio_player script

func level_changed():
	var scene_name = get_tree().get_current_scene().name

	if (scene_name == "StartMenu"):
		music_player.stream = title_music
		music_player.play()
	else:
		if (music_player.stream == title_music):
			music_player.stream = level_music
			music_player.play()

so when any level is loaded, its ready is called, then they run this level_changed() method.

it will check if the scene name is startMenu, if it is, play the start menu music.
if not it will check to see if the already allocated stream name is the level music, if it is, does nothing,
but if it was set to something else, it will set the bg music and play.

see how you get on with that, hope its what your looking for

Darren

2 Likes

Fantastic! That did the trick, thank you so much!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms