Play Audio on event

Hey guys, ive been lewrning lua for a few months and nust finished the first tutorial and moving on to the second one. However ive checked the video tutorials and text tutorials and im kind of stuck on how to get audio to play on an event. Like say i pickup a weapon and i want the audio weaponfound.mp3 to play. How would i do this in lua

1 Like

I use the method with a soundgate, and a gameobject storing sounds, and then send a msg.post to the soundgate on the event. You can read about it in the manual, at http://www.defold.com/manuals/sound/. Scroll towards the bottom. :+1:

By the way, I convert all my audio into .ogg. Defold only support .ogg and .wav, I believe.

A small trick I use; to randomize audio response, I use an array to store the possible sound, and randomize the picking of the sound. A real world example, is my first prototype, where I sampled my son laughing and saying “One more time”. The prototype is based on the starting tutorial, starring my son instead of the frog. When he jumps, I play a sound.[ http://rsletta.github.io/RunSamuelRun/index.html ] Code example(from player_controller.script):

...
local laughs = {"laugh1","laugh2","laugh3","laugh4","onemore"}
...

local function jump(self)
...
        -- Play laughing sound
        local pickedLaugh = "/sounds#" .. laughs[ math.random( #laughs ) ]
	msg.post("/sound_gate#script", "play_gated_sound", { soundcomponent = pickedLaugh, gain = 1 })
...
end
10 Likes