Music Example

require 'gosu'

class MusicExample < Gosu::Window
    def initialize
        super 640, 480
        self.caption = "Music Example"
        @font =, name: "Nimbus Mono L")
        @music ="./music.ogg")
    def draw
        @font.draw("Music Playing: %s" % @music.playing?, 20, 20, 0)
        @font.draw("Press 'M' to toggle the music.", 20, 52, 0)
    def button_up(keycode)
        if keycode == Gosu::KbM then
            if @music.playing? then

A brief word about sound: Gosu supports two types of sounds- Samples and Songs. Samples are used for short sound effects. Songs are used for music or longer sound effects.

The reason why we distinguish between the two has to do with memory- how much your computer can fit in its ‘brain’ before it has to write something down. A short sound effect is relatively small and its easy for your computer to load it into memory.

Music files, on the other hand, can be quite large, so Gosu will stream them instead of loading the entire song into memory. This is kind of like how we can easily memorize phrases, but longer notes or speeches we often write down and refer to as needed.

If you really dig into Gosu you can see this difference play out in that when we call Sample#play, Gosu returns a SampleInstance class which represents that particular time you are playing the sound effect. If you have a sound effect for something like an engine or footsteps, you could potentially have multiple SampleInstances playing at once. Songs on the other hand only get loaded once- you shouldn’t have multiple copies of a Song.