Class: Musikov::MidiWriter

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

Overview

This class is responsible for interacting with MidiLib in order to write the output midi files.

Instance Method Summary collapse

Constructor Details

#initialize(output_path = ".") ⇒ MidiWriter

Initializes the parser using the output path parameter

  • Parameter need to be a folder folder



17
18
19
# File 'lib/musikov/midi_writer.rb', line 17

def initialize(output_path = ".")
  @path = output_path
end

Instance Method Details

#write(sequence_hash) ⇒ Object

Writes the output midi file from the generated sequence hash



22
23
24
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
# File 'lib/musikov/midi_writer.rb', line 22

def write(sequence_hash)
  # Create a new, empty sequence.
  seq = MIDI::Sequence.new()
  
  track = MIDI::Track.new(seq)
  seq.tracks << track
  track.events << MIDI::Tempo.new(MIDI::Tempo.bpm_to_mpq(120))
  i = 0
  
  # Create a track to hold the notes. Add it to the sequence.
  sequence_hash.each { |program_change, midi_elements|
    track = MIDI::Track.new(seq)
    seq.tracks << track
    
    instrument = MIDI::GM_PATCH_NAMES[program_change]
  
    # Give the track a name and an instrument name (optional).
    track.instrument = instrument
  
    # Add a volume controller event (optional).
    track.events << MIDI::Controller.new(i, MIDI::CC_VOLUME, 127)
    track.events << MIDI::ProgramChange.new(i, program_change, 0)
    midi_elements.each { |midi_element|
      track.events << MIDI::NoteOn.new(i, midi_element.note ,127,0)
      track.events << MIDI::NoteOff.new(i, midi_element.note ,127, seq.note_to_delta(midi_element.duration))
    }

    i += 1
  }
  
  write_midi(seq)
end