class Eagle::Sound

Overview

A sound effect or music track loaded into memory. Play it as often as you like; each #play returns a Voice that you can adjust or stop independently.

Eagle decodes WAV and Ogg Vorbis in pure Crystal, and can synthesize simple sounds, which is great for prototypes and jams.

jump = Sound.load("res://sfx/jump.wav")
jump.play(volume: 0.8, pitch: 0.9 + rand * 0.2) # small pitch variation sounds natural

music = Sound.load("res://music/theme.ogg")
voice = music.play(loop: true, bus: "music")
voice.fade(0, 2.0) # fade out over two seconds

beep = Sound.tone(880, 0.15, Sound::Wave::Square, volume: 0.3)
laser = Sound.generate(0.3) { |t| Math.sin(t * 2000 * (1 - t * 2)).to_f32 * (1 - t / 0.3) }

Sounds are fully decoded into memory. That is fine for effects and short loops; long tracks cost a few tens of megabytes each.

Defined in:

eagle/audio/audio.cr

Constructors

Instance Method Summary

Constructor Detail

def self.decode(data : Bytes, hint : String = "") : Sound #

Decodes WAV or Ogg Vorbis bytes, detecting the format from the data.


def self.generate(duration : Number, sample_rate : Int32 = Audio::SAMPLE_RATE, name : String = "generated", &block : Float32 -> Float32) : Sound #

Synthesizes a mono sound sample by sample. The block receives the time in seconds and returns a sample from -1 to 1.


def self.load(path : String) : Sound #

Loads a WAV or Ogg Vorbis file through the asset cache.


def self.new(buffer : AudioBuffer, name : String = "sound") #

Wraps an AudioBuffer.


def self.tone(frequency : Number, duration : Number, wave : Wave = Wave::Sine, volume : Number = 0.5, attack : Number = 0.005, release : Number = 0.02, sample_rate : Int32 = Audio::SAMPLE_RATE) : Sound #

A single note of frequency Hz with a short fade in and out, so it doesn't click. Handy for UI beeps and chiptune effects.


Instance Method Detail

def buffer : AudioBuffer #

The decoded samples.


def duration : Float32 #

Length in seconds.


def name : String #

A label for debugging: the file path for loaded sounds.


def play(volume : Number = 1, pitch : Number = 1, pan : Number = 0, loop : Bool = false, bus : String = "master") : Voice #

Starts playing the sound and returns its Voice. pitch 2 is an octave up and 0.5 an octave down. pan runs from -1 (left) to 1 (right). bus groups voices for volume control.


def save(path : String) : Nil #

Writes the sound as a 16-bit WAV file.