Class: Muse::Song

Inherits:
Object
  • Object
show all
Defined in:
lib/muse.rb

Defined Under Namespace

Classes: Bar

Class Method Summary collapse

Class Method Details

.bar(id, options = {}) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
# File 'lib/muse.rb', line 143

def bar(id, options={})
  puts "bar #{id}"
  unless @bars[id]
    @bars[id] = []
  end
  options[:bpm] = options[:bpm] || @bpm || 120
  options[:envelope] = options[:envelope] || @envelope || 'default'
  options[:harmonic] = options[:harmonic] || @harmonic || 'default'
  @bars[id] << Bar.new(id, options)
  @bars[id].last
end

.record(name, options = {}, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/muse.rb', line 24

def self.record(name, options ={}, &block)
  start_time = Time.now
  puts "Start recording song named #{name}.wav"
  @name = name
  @bpm = options[:bpm] || 120
  @envelope = options[:envelope] || 'default'
  @harmonic = options[:harmonic] || 'default'
  @bars = {}
  puts "Processing ..."
  instance_eval &block
  save
  end_time = Time.now
  puts "Total time taken : #{((end_time - start_time)/60.0).round(3)} minutes"  
  puts "done."
end

.right_size(bars) ⇒ Object



155
156
157
158
159
160
161
162
# File 'lib/muse.rb', line 155

def right_size(bars)
  container = []
  min_bar = bars.min_by {|x| x.stream.length}
  bars.map do |bar|
    bar.truncate_stream_by(bar.stream.length - min_bar.stream.length)
    bar
  end
end

.saveObject



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/muse.rb', line 164

def save
  puts "Creating temporary files in parallel ..."

  results = Parallel.each_with_index(@bars.values, :in_processes => Parallel.processor_count) do |item, id|
    puts "Writing file - #{id}"
    stream = []
    container = []
    item = right_size item
    item.each do |i|
      container << i.stream
    end
    stream += container.transpose.map {|x| x.transpose.map {|y| y.reduce(:+)}}
    temp = TempData.new
    stream.each_with_index do |s,i|
      temp.stream[i].left = s[0]
      temp.stream[i].right = s[1]
    end          
    File.open("#{@name}-#{id.to_s.rjust(3,'0')}.tmp", "w") {|file| temp.write(file) }
    puts "Completed file - #{id}"
  end

  stream_size = results.inject(0) do |memo, bars|
    memo + bars.first.stream.size
  end

  puts "Combining temporary files ..."
  WavHeader.new("#{@name}.wav", stream_size)
  tmpfiles = Dir.glob("#{@name}-*.tmp").sort
  File.open("#{@name}.wav", "ab+") do |wav|
    tmpfiles.each do |file|
      File.open(file, "rb") { |tmp| File.copy_stream(tmp, wav) }
      File.delete file
    end
  end
  
end