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 Music

As usual with DragonRuby, the simple stuff is simple.

To play a looping sound, for example as background music, get a sound file in .ogg format and then add it on to args.outputs.sounds:

args.outputs.sounds << 'sounds/my_music.ogg'
Enter fullscreen mode Exit fullscreen mode

The audio will loop forever.

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.

Wait so the API behaves differently based on the file format?

Yep. A little odd but it works.

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 a .wav or not loop a .ogg file?

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: false  # Don't loop
}
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: false
}
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!

Oldest comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈