Music not loading in the export

Godot Version

4.5

Question

I’m making a game where a music track is randomly selected and played. Everything works fine in the engine, but in the exported build, the music won’t play at all. Strangely, other sound effects work perfectly. here is the code for the music, which is inside the player script:

@onready var music=$AudioStreamPlayer2D
@onready var engin=$engine
func _ready():
	load_random_music()
	if music.stream != null:
		
		music.play()


var last_played_music = ""

func load_random_music():
	var dir = DirAccess.open("res://music/")
	if dir:
		var music_files = []
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			# Only add files with audio extensions
			if file_name.ends_with(".ogg") or file_name.ends_with(".wav") or file_name.ends_with(".mp3"):
				music_files.append("res://music/" + file_name)
			file_name = dir.get_next()
		dir.list_dir_end()

		# If we found music files, try to load them one by one until one works
		if music_files.size() > 0:
			var available_files = music_files.duplicate()
			if last_played_music != "" and available_files.size() > 1:
				available_files.erase(last_played_music)
			
			# Shuffle the available files to get random order
			available_files.shuffle()
			
			var loaded_successfully = false
			var attempts = 0
			var max_attempts = min(available_files.size(), 10) 
			
			while not loaded_successfully and attempts < max_attempts:
				var music_stream = load(available_files[attempts])
				if music_stream and music_stream is AudioStream:
					music.stream = music_stream
					loaded_successfully = true
					last_played_music = available_files[attempts]  
					print("Loaded music: ", available_files[attempts])
				else:
					print("Failed to load music file: ", available_files[attempts])
					attempts += 1
			
			if not loaded_successfully:
				print("Could not load any music files after ", attempts, " attempts")
		else:
			print("No music files found in res://music folder")
	else:
		print("Error: Could not open music directory")

in the export console it says “No music files found in res://music folder”. so what should I do? should I send the music folder with the export or something?

How do you export the game? You might have to add the folder/files manually in the export options.

I could be wrong but music that lives within the PCK file when you export should NOT be accessed with normal IO functions, but instead you should load them using the ResourceLoader, since they’re considered a resource.

2 Likes

DirAccess works for me too in the build, as long as it tries to access a res:// folder.

1 Like

I’ve been having weird issues similar to this with web exports only since 4.5. Is this a web export?

nope, its pc export.

1 Like