How to load and play multiple sounds at once?

Hi,

I’m using this code to load sounds dynamically at runtime.

if message_id == hash("loadsound") then
	pprint(message)
	local wav = sys.load_resource("/main/bundled_resources/common/"..message.sounddirectory.."/"..message.soundfilename..".wav") --sounds/clock-ticking.wav")
	print("Loaded:"..message.soundfilename..".wav")
	-- get resource path to the sound component
	local resource_path = go.get("/"..message.soundbank.."#"..message.soundbank, "sound")
	-- update the resource with the loaded wav file
	resource.set_sound(resource_path, wav)
	print("new sound ready!")
end

But I’m not getting multiple sounds to play at once when called likely in the same frame. I’m sure it’s some weird thing where I’m not addressing or properly maintaining two sound banks/buffers/objects but I’m not sure much else so far…

So I just figured this out to some degree but I’m not sure to explain why this is the solution.

In the set up for the game objects that are individually addressed for each sound channel the “placeholder” sound effect field set in Sound must be different.

I’m not sure I’m describing this great but initially you set up an object and attach sounds to it and those sounds are addressable, but in order to compile the game pre-set sounds must be attached to each one (e.g. a wav file) and that might be like “lasersound.wav” but if each individual sound channel you intend to use is all set to lasersound.wav at design time it won’t play multiple effects. So you would need sounditem1 = lasersound1.wav sounditem2 = lasersound2.wav and so on. Even though you’ll be replacing the actual files dynamically at run time, they need to be different at design time.

At least once I did this I got simultaneous playback of two different sounds.

This is correct. The sound component has a reference to a sound resource. If two sound components refer to the same sound resource (ie same file from your assets) it will not be loaded twice. The components will refer to the exact same data.

And resource.set_sound() will change the data in the sound resource referenced by a sound component. So with this in mind it makes sense that the two sound components both will use the new sound.

2 Likes

What I did was create a 3 second silent wav file and I named the 8 instances to each of my “banks” so I have a silent wave file attached to the game object at design time titled:

backgroundmusic
ambient1
ambient2
VoiceOver
effect1
effect2
effect3
effect4

since each are distinct sounds when I replace them with the runtime file the problem is solved. I might eventually replace them with a voice over that says “error: new file not loaded.” for feedback but for now it’s all good.

2 Likes