Class: Musicality::RandomRhythmGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/musicality/composition/generation/random_rhythm_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(palette_with_probs) ⇒ RandomRhythmGenerator

Returns a new instance of RandomRhythmGenerator.



6
7
8
9
# File 'lib/musicality/composition/generation/random_rhythm_generator.rb', line 6

def initialize palette_with_probs
  @durations, @probabilities = palette_with_probs.entries.transpose
  @dur_sampler = RandomSampler.new(@durations,@probabilities)
end

Instance Attribute Details

#durationsObject (readonly)

Returns the value of attribute durations.



4
5
6
# File 'lib/musicality/composition/generation/random_rhythm_generator.rb', line 4

def durations
  @durations
end

#probabilitiesObject (readonly)

Returns the value of attribute probabilities.



4
5
6
# File 'lib/musicality/composition/generation/random_rhythm_generator.rb', line 4

def probabilities
  @probabilities
end

Instance Method Details

#random_durObject



11
12
13
# File 'lib/musicality/composition/generation/random_rhythm_generator.rb', line 11

def random_dur
  @dur_sampler.sample
end

#random_rhythm(target_dur, end_retries = 5) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/musicality/composition/generation/random_rhythm_generator.rb', line 15

def random_rhythm target_dur, end_retries = 5
  rhythm = []
  total_dur = 0
  retries = 0
  
  while(total_dur < target_dur && retries < end_retries)
    dur = random_dur
    
    if (dur + total_dur) <= target_dur
      total_dur += dur
      rhythm.push(dur)
    else
      retries += 1
    end
  end
  
  if total_dur < target_dur
    rhythm.push(target_dur - total_dur)
  end
  
  return rhythm
end