DEV Community

Justin
Justin

Posted on • Updated on • Originally published at blog.presidentbeef.com

Sounds in DragonRuby

The sound API in DragonRuby is a little tricky because at first it seems similar to the sprite API (e.g. using args.outputs) but it diverges sharply when you want to have some more control.

So let's take a quick look at audio in DragonRuby!

Simple Sound Effects

Want to fire off a single sound effect?

Get a sound file in .wav format and then add it on to args.outputs.sounds:

args.outputs.sounds << 'sounds/my_effect.wav'
Enter fullscreen mode Exit fullscreen mode

The sound will play once. This is great for one-off sound effects.

Sound Formats

DragonRuby supports wav and ogg file formats.

In versions of DragonRuby before 5.0, wav files would be played once by default, while ogg files would loop. This is no longer the case.

For the args.outputs.sounds API, both wav and ogg files will now only be played once.

Adjusting the Volume Knob

Playing a sound effect in DragonRuby is pretty easy. But what if we need to adjust the volume or some other attribute of the audio? Or maybe loop the audio?

You might think, based on how sprites work in DragonRuby, you could do something like this:

# This does not work!
args.outputs.sounds << {
  input: 'sounds/my_music.ogg',
  gain: 0.5,      # Half volume
  looping: true  # Loop the audio
}
Enter fullscreen mode Exit fullscreen mode

But this does not work.

Instead, you need to use an entirely different interface: args.audio.

args.audio is a hash table of sounds.

To add a new sound, assign it with a name:

args.audio[:music] = {
  input: 'sounds/my_music.ogg',
  gain: 0.5,
  looping: true
}
Enter fullscreen mode Exit fullscreen mode

To adjust an attribute of the audio, access it by the same name:

# Turn up the volume
args.audio[:music].gain = 0.75
Enter fullscreen mode Exit fullscreen mode

To pause a sound:

args.audio[:music].paused = true
Enter fullscreen mode Exit fullscreen mode

To completely remove a sound:

args.audio.delete :music
Enter fullscreen mode Exit fullscreen mode

More Music Manipulation

This is the full set of options for audio from the documentation:

args.audio[:my_music] = {
  input: 'sounds/my_music.ogg',
  x: 0.0, y: 0.0, z: 0.0,   # Relative position to the listener, x, y, z from -1.0 to 1.0
  gain: 1.0,                # Volume (0.0 to 1.0)
  pitch: 1.0,               # Pitch of the sound (1.0 = original pitch)
  paused: false,            # Set to true to pause
  looping: false,           # Set to true to loop
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Top comments (0)