How to play a sound (SOLVED)

I am struggling with how to get a sound to play the manual post doesn’t`` make any sense to me I get what its for but it never actually says how to play a sound or where to put it.

function init(self)
   msg.post("ground/controller#script", "set_speed", { speed = self.speed })
   self.gridw = 0  
   msg.post("play_gated_sound",{ soundcomponent = "/sounds#music", gain = 1.0 })
end

this is what ive got but the sound doesn’t play, I have a game object with sound component all name music, i would love some help please and thank you

1 Like

You send the sound component the “play_sound” message.

-- assuming game object "music" has a component "sound"
msg.post("music#sound", "play_sound", {delay = 1, gain = 0.5})

See http://www.defold.com/ref/sound/

3 Likes

To use your code, you have to create the sound_gate script, and attach that to a sound_gate object. Then it will work. :+1:

It in the last part of the sound section of the sound manual. http://www.defold.com/manuals/sound/

4 Likes

thank for the help ill give it a try

1 Like

I am having the no sound problem, but my setup is much simpler. I have sounds, I send the message above to a script (essentially a blank script, it has the on_message function empty). I put a print statement in the on_message, and it shows that it received the message. But no sound. I have played with gain (documentation very confusing here – gain usually means positive dB, but you can only put negative numbers on the sound component), but I have tried many different variations, even setting the group gain (sound.set_group_gain(“master”, 2.5). The sounds are all .ogg files and work fine in other applications. Is there some setting I am missing?

Mac OSX, playing directly from dmengine. Possibly sounds only work on devices and HTML5?

Nope, works on my Mac at least. Would you mind trying one of these examples on your machine:

Thank you, nothing like an example. Yours worked, and now mine works. I was sending msg to the script on the same go as the sound, but I have to send it directly to the sound, script is irrelevant. I am quite sure the documentation says to post the msg to a script, but I probably misunderstood. Thank you.

Good that you got it working! The documentation for play_sound mentions that the message should be posted to the sound component:

“Post this message to a sound-component to make it play its sound.”