Playing Music

No game is complete without a bit of audio… how about we add some music to our game? I linked to the ogg vorbis (an audio compression format) sound file I downloaded, but you can obviously use whatever sound file you want for the background music. Audio files in Defold can either be .ogg or .wav. The .ogg format is compressed and is ideal for longer sounds, such as music or dialog. It takes up less space but takes more processor to decompress and play. The .wav format, on the other hand, is much simpler but also much bigger. Use .wav for small but often used sound effects like um… sound effects.

Whichever format you choose, the process of importing it is exactly the same, simply drag and drop the audio file into your assets folder. Once we’ve added the asset, it’s time to use it.

Open up main.collection, then right-click the player game object, select Add Component and choose Sound.

Adding a Sound

Now select your newly added sound, go to properties, and in the Sound field, select your recently attached ogg file. Since we are using this as our soundtrack and we only have one song, let’s set the Looping property to true so when the song ends playing it will start over again automatically.

Setting the soundtrack

And now to the code…. Open up main.script and change the code to match the following:

function init(self)
	collectionfactory.create("#collectionfactory")"#sound", "play_sound")

As you can see, playing audio is just like everything else in Defold, just send the sound component a message to play the sound. And done. Play your game and you should now have a soundtrack… I’d showcase a screenshot, but yeah… audio and all that.

We are only going to cover the basics of playing sound in Defold. If you want to get more in-depth, check the documentation available here.

Scroll to Top