Class: Beats::AudioEngine
- Inherits:
-
Object
- Object
- Beats::AudioEngine
- Defined in:
- lib/beats/audioengine.rb
Overview
This class actually generates the output audio data that is saved to disk.
To produce audio data, it needs two things: a Song and a Kit. The Song tells it which sounds to trigger and when, while the Kit provides the sample data for each of these sounds.
Example usage, assuming song and kit are already defined:
engine = AudioEngine.new(song, kit)
engine.write_to_file("my_song.wav")
Constant Summary collapse
- SAMPLE_RATE =
44100
- PACK_CODE =
All output sample data is assumed to be 16-bit
"s*"
Instance Attribute Summary collapse
-
#step_sample_length ⇒ Object
readonly
Returns the value of attribute step_sample_length.
Instance Method Summary collapse
-
#initialize(song, kit) ⇒ AudioEngine
constructor
A new instance of AudioEngine.
- #write_to_file(output_file_name) ⇒ Object
Constructor Details
#initialize(song, kit) ⇒ AudioEngine
Returns a new instance of AudioEngine.
17 18 19 20 21 22 23 |
# File 'lib/beats/audioengine.rb', line 17 def initialize(song, kit) @song = song @kit = kit @step_sample_length = AudioUtils.step_sample_length(SAMPLE_RATE, @song.tempo) @composited_pattern_cache = {} end |
Instance Attribute Details
#step_sample_length ⇒ Object (readonly)
Returns the value of attribute step_sample_length.
58 59 60 |
# File 'lib/beats/audioengine.rb', line 58 def step_sample_length @step_sample_length end |
Instance Method Details
#write_to_file(output_file_name) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/beats/audioengine.rb', line 25 def write_to_file(output_file_name) packed_pattern_cache = {} num_tracks_in_song = @song.total_tracks # Open output wave file and prepare it for writing sample data. format = WaveFile::Format.new(@kit.num_channels, @kit.bits_per_sample, SAMPLE_RATE) writer = WaveFile::CachingWriter.new(output_file_name, format) # Generate each pattern's sample data, or pull it from cache, and append it to the wave file. incoming_overflow = {} @song.flow.each do |pattern_name| key = [pattern_name, incoming_overflow.hash] unless packed_pattern_cache.member?(key) sample_data = generate_pattern_sample_data(@song.patterns[pattern_name], incoming_overflow) packed_pattern_cache[key] = { :primary => WaveFile::Buffer.new(sample_data[:primary], format), :overflow => WaveFile::Buffer.new(sample_data[:overflow], format) } end writer.write(packed_pattern_cache[key][:primary]) incoming_overflow = packed_pattern_cache[key][:overflow].samples end # Write any remaining overflow from the final pattern final_overflow_composite = AudioUtils.composite(incoming_overflow.values, format.channels) final_overflow_composite = AudioUtils.scale(final_overflow_composite, format.channels, num_tracks_in_song) writer.write(WaveFile::Buffer.new(final_overflow_composite, format)) writer.close() writer.total_duration end |