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



148
149
150
151
152
153
154
155
156
157
158
# File 'lib/muse.rb', line 148

def bar(id, options={})
  puts "bar #{id} - bpm:#{@bpm}"
  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



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/muse.rb', line 43

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



160
161
162
163
164
165
166
167
# File 'lib/muse.rb', line 160

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



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
200
201
202
203
204
# File 'lib/muse.rb', line 169

def save
  puts "\nCreating 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 "file #{id} done."
  end

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

  print "\nCombining 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
  puts " done."
end