Class: MusicTheory::Note

Inherits:
Object
  • Object
show all
Includes:
Output
Defined in:
lib/music_theory/note.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Output

#buffer_format, #format, #output_track, #play, #sample_rate

Constructor Details

#initialize(options = {}) ⇒ Note

Returns a new instance of Note.



8
9
10
11
12
13
14
# File 'lib/music_theory/note.rb', line 8

def initialize(options = {})
  @frequency        = options[:frequency] || 440.0          # Note frequency in Hz
  @frequency        = @frequency.to_f
  @duration         = options[:duration] ||  1.0            # Number of seconds per note
  @distort          = options[:distort] || false
  @output_file_name = options[:output_file_name] || 'note'  # File name to write (without extension)
end

Instance Attribute Details

#distortObject

Returns the value of attribute distort.



6
7
8
# File 'lib/music_theory/note.rb', line 6

def distort
  @distort
end

#durationObject

Returns the value of attribute duration.



6
7
8
# File 'lib/music_theory/note.rb', line 6

def duration
  @duration
end

#frequencyObject

Returns the value of attribute frequency.



6
7
8
# File 'lib/music_theory/note.rb', line 6

def frequency
  @frequency
end

#output_file_nameObject

Returns the value of attribute output_file_name.



6
7
8
# File 'lib/music_theory/note.rb', line 6

def output_file_name
  @output_file_name
end

Instance Method Details

#cycles_per_frameObject



21
22
23
24
# File 'lib/music_theory/note.rb', line 21

def cycles_per_frame
  # each frame, we want this fraction of a cycle:
  frequency / sample_rate
end

#distort!(samples) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/music_theory/note.rb', line 43

def distort!(samples)
  samples.map do |sample|
    negative = sample < 0
    sample *= 8.to_f
    if sample.abs > 5
      sample = 5
      sample *= -1 if negative
    end
    sample /= 8.to_f
  end
end

#samplesObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/music_theory/note.rb', line 31

def samples
  # So to create a note that's one second long, we need to write out all the samples in the sine waves
  phase = 0
  samples = total_frames.times.map do
    sample = (Math.sin phase).to_f
    phase += sine_wave_cycle
    sample
  end
  samples = distort!(samples) if distort
  samples
end

#sine_wave_cycleObject



26
27
28
29
# File 'lib/music_theory/note.rb', line 26

def sine_wave_cycle
  # A cycle is a full sine wave, which is 2π radians:
  2 * Math::PI * cycles_per_frame
end

#total_framesObject



16
17
18
19
# File 'lib/music_theory/note.rb', line 16

def total_frames
  # We want 1 second of the note, so we need 1 second's worth of frames
  (duration * sample_rate).to_i
end