Ruby makes music
Sound is air that vibrates. A loudspeaker pushes its cone back and forth, and how fast it does so is what you hear as pitch: 440 times a second is the concert A an orchestra tunes to.
A computer describes that movement with numbers: it measures it 22,050 times a second (the sample rate) and writes down where the cone is each time – a number between -1 and 1. One second of sound is simply an Array of 22,050 Floats. In this lesson you compute that Array yourself, without any gem: first a tone, then a melody, chords and a drum kit.
RATE = 22_050 # numbers per second
concert_a = Array.new(RATE) do |i| # one second
time = i.fdiv(RATE) # in seconds
0.5 * Math.sin(2 * Math::PI * 440 * time)
end
concert_a.first(8).map { |s| s.round(3) }Array.new(RATE) { |i| … } calls the block 22,050 times and collects what it returns. i.fdiv(RATE) turns the number's position into the time in seconds, and Math.sin(2 * Math::PI * 440 * time) is a sine wave that goes up and down once, 440 times a second. Times 0.5 makes it half as loud.
But you cannot listen to an Array – the browser wants a WAV file. That is surprisingly simple: a 44-byte header, then every number as a whole number from -32,768 to 32,767.
def wav(samples)
data = samples.map { |s| (s.clamp(-1.0, 1.0) * 32_767).round }.pack("s<*")
header = ["RIFF", 36 + data.bytesize, "WAVE",
"fmt ", 16, 1, 1, RATE, RATE * 2, 2, 16, # PCM, 1 channel, 16 bits
"data", data.bytesize].pack("a4Va4a4VvvVVvva4V")
header + data
end
file = wav(concert_a)
show_audio file
[file.bytesize, file[0, 4], file[8, 4]]pack turns an Array into bytes, and the text in brackets says how: s<* means "every number as a signed 16-bit number, low byte first". For the header each letter stands for one field: a4 is 4 characters of text, V a 32-bit number, v a 16-bit number. They hold the length of the file, the format (1 = PCM, raw numbers), 1 channel, the sample rate and 16 bits per number. 44 bytes of header plus 2 bytes per number: 44,144 bytes for one second.
With pack and unpack Ruby reads and writes almost any binary format – PNG, ZIP and MIDI work the same way. show_audio plays the file below the cell and shows the wave: the whole sound on the left, 12 milliseconds under the magnifier on the right.
WAVES = {
sine: ->(phase) { Math.sin(2 * Math::PI * phase) },
square: ->(phase) { phase < 0.5 ? 1.0 : -1.0 },
saw: ->(phase) { 2 * phase - 1 }
}
def tone(frequency, seconds, wave = :sine, volume = 0.3)
shape = WAVES.fetch(wave)
Array.new((seconds * RATE).round) do |i|
volume * shape.((frequency * i).fdiv(RATE) % 1.0) # where in the vibration?
end
end
WAVES.each_key { |wave| show_audio wav(tone(220, 0.6, wave)) }
WAVES.keysThe phase says where in one vibration you are: 0.0 at the start, 0.5 halfway, just under 1.0 at the end. (frequency * i).fdiv(RATE) % 1.0 works it out – % throws away the whole vibrations and keeps the rest. Every wave is a lambda that turns the phase into a height, and all three live in a Hash. A new sound colour is one more line.
Look through the magnifier: the sine is round and sounds soft, square and saw have corners and buzz like a Game Boy – corners are made of many higher tones, the overtones. That is also why they are computed quieter.
STEPS = { "C" => 0, "D" => 2, "E" => 4, "F" => 5, "G" => 7, "A" => 9, "B" => 11 }
def frequency(name) # "A4" → 440.0
semitone = 12 * (name[1].to_i + 1) + STEPS.fetch(name[0])
440 * 2**((semitone - 69) / 12.0)
end
def envelope(samples) # fade in and out: no clicks
n = samples.size
samples.each_with_index.map { |s, i| s * [1.0, i / 200.0, (n - i) / 800.0].min }
end
def notes(text, length: 0.25, wave: :sine)
text.split.flat_map do |name|
if name == "-"
Array.new((length * RATE).round, 0.0) # a rest
else
envelope(tone(frequency(name), length, wave))
end
end
end
frog_song = notes("C4 D4 E4 F4 E4 D4 C4 - E4 F4 G4 A4 G4 F4 E4 -", length: 0.3)
show_audio wav(frog_song)
[frequency("A4"), frequency("C4").round(1), frequency("C5").round(1)]That is the frog song, a German children's song that every child in Japan knows as 「かえるの歌」. A melody is a String here: split cuts it into note names, and flat_map joins the tones of all the notes into one long Array.
An octave has 12 semitones, and each semitone is 21/12 ≈ 1.059 times higher than the one before – after 12 steps the frequency has exactly doubled: C5 vibrates twice as fast as C4. frequency counts the semitones from A4 (number 69, as in MIDI) and works out the frequency from that. And envelope fades each tone in and out briefly: when a wave jumps to zero in the middle of a vibration, you hear a click. Delete the envelope(…) once and listen.
def mix(*tracks)
longest = tracks.map(&:size).max
tracks = tracks.map { |track| track + [0] * (longest - track.size) }
tracks.first.zip(*tracks.drop(1)).map(&:sum)
end
c_major = mix(*%w[C4 E4 G4].map { |name| envelope(tone(frequency(name), 1.5, :sine, 0.2)) })
show_audio wav(c_major)
mix([1, 2, 3], [10, 20], [100])When several tones sound at once, the air pressure simply adds up. zip lays the Arrays side by side – [1, 2].zip([10, 20]) gives [[1, 10], [2, 20]] – and map(&:sum) adds up each pair. Before that, mix pads shorter tracks with silence. The chord C-E-G is C major.
That is why every tone here plays at only 0.2: three tones at 0.5 would reach 1.5, and clamp cuts off everything above 1 – it sounds harsh (clipping). Try it.
def kick # a sine falling from 120 to 40 Hz
phase = 0.0
Array.new(3000) do |i|
time = i.fdiv(RATE)
phase += (40 + 80 * Math.exp(-time * 30)) / RATE
0.8 * Math.sin(2 * Math::PI * phase) * Math.exp(-time * 15)
end
end
def hihat # noise that dies away fast
Array.new(1200) { |i| 0.2 * (rand * 2 - 1) * Math.exp(-i / 150.0) }
end
def drums(pattern, step: 0.125)
slot = (step * RATE).round
pattern.chars.flat_map do |char|
sound = case char
when "x" then kick
when "h" then hihat
else []
end
sound.first(slot) + [0.0] * [slot - sound.size, 0].max
end
end
beat = drums("x.h.x.h.x.h.xxh." * 2)
melody = notes("C4 D4 E4 F4 E4 D4 C4 - E4 F4 G4 A4 G4 F4 E4 -", wave: :square)
song = mix(melody, beat)
File.binwrite("frog_song.wav", wav(song))
show_audio "frog_song.wav"A drum kit is a String again: every character is an eighth note, x the bass drum, h the hi-hat, a dot a rest. The kick is a sine whose frequency falls fast while it dies away (Math.exp(-time * 15) shrinks quickly), the hi-hat is noise from rand. Every sound is cut to its slot or padded with silence, so the beat stays even.
notes, drums, mix – those are already the words of a small language for music, built from Arrays, Strings and blocks (more in lesson 121, "Your own DSL"). File.binwrite writes the bytes as a file; it appears below the cell as a download, and show_audio takes its name too.
The same code runs there: File.binwrite("song.wav", wav(song)), then open the file in any player. To read WAV files as well, or write stereo and 24 bits, use the wavefile gem (pure Ruby, it runs here too with install_gem "wavefile") – for this song it writes the very same file, byte for byte.
fanfare.wav: first the notes C4, E4, G4 and C5 one after another, 0.25 seconds each, then all four together for one second – 2 seconds in all.# fanfare.wav: C4 E4 G4 C5 one after another (0.25 s each), then all four together (1 s)