Diapason

Music with Ruby.

Install

Install it directly: gem install diapason

Or put it in your Gemfile: gem 'diapason'

Use

require 'diapason'

# A (La) 440Hz
tonic = Diapason::Note.a440

# Tuning system used for pianos and other keyboard instruments
twelve_tone_equal_temperament = Diapason::Tuning::EqualTemperament.new(12, tonic)

# Generates the 12 notes with their respective frequencies (the chromatic scale)
notes = twelve_tone_equal_temperament.notes

# Builds the C (Do) major scale
# 2 = tone, 1 = semitone
major_scale_intervals = [2, 2, 1, 2, 2, 2, 1]
c_major = notes[3]
c_major_scale = Diapason::Scale.build(notes, major_scale_intervals, c_major)

# Generates sine waves (like those from tunning forks) from each note of the scale
waves = c_major_scale.notes.map do |note|
  Diapason::Sound::SineWave.from_note(note)
end

# Since continuous signals (like audio waves) can't be exactly represented by
# digital means (like files) we need to sample it (pick some points of the wave
# to represent it) at some sample rate. 44100Hz is used by CD's.
sample_rate = 44100

# Samples any kind of sinusoidal waves, like sine waves or cosine waves
sampler = Diapason::Sound::SinusoidalWaveSampler.new(sample_rate)

# Builds 1 second worth of samples for each wave (note)
samples = waves.map do |wave|
  sampler.samples_for_duration(wave, 1)
end

# Writes wave file
writer = Diapason::Sound::WaveFileWriter.new(sample_rate)
file = writer.write_samples(samples.map(&:to_a).flatten, '/path/to/c_major_scale.wav')

# Plays the file
Diapason::Sound::WaveFilePlayer.new.play(file)