Class: MidiWriter

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

Overview

writes sequences of noteData (from a RhythmParser class) to midi tracks a ‘MidiWriter’ represents one midi Song, which can be written to one file, the midiSong can contain multiple tracks/noteSequences

Returns:

  • (Object)

    MidiWriteInstance instance of the midi writer. creator of one midi file with potential multiple tracks

Instance Method Summary collapse

Constructor Details

#initialize(bpm) ⇒ MidiWriter

Returns a new instance of MidiWriter.



20
21
22
23
# File 'lib/rhythmruby/MidiWriter.rb', line 20

def initialize(bpm)
  @song = MIDI::Sequence.new() # this is a midi song/sequence
  @bpm = bpm # beats per minute of the midi song/sequence
end

Instance Method Details

#createTrackMIDI::Track

creates a track within the midi song of current MidiWriter instance

Returns:

  • (MIDI::Track)

    newTrack a new track within the midi song



27
28
29
30
31
32
# File 'lib/rhythmruby/MidiWriter.rb', line 27

def createTrack()
   @song.tracks << (newTrack = MIDI::Track.new(@song))
   newTrack.events <<  MIDI::Tempo.new(MIDI::Tempo.bpm_to_mpq(@bpm))
   newTrack.events << MIDI::ProgramChange.new(0, 0)
   return newTrack
end

#writeNote(midiNote, noteLength, midiTrack) ⇒ Object

writes one midiNote to a midiTrack

Parameters:

  • midiNote (Fixnum)

    of the event to be written to a midiTrack

  • noteLength (Float)

    length of the midiEvent, in multiples of the quarternote

  • midiTrack (MIDI::Track)

    where the event is written to



49
50
51
52
53
# File 'lib/rhythmruby/MidiWriter.rb', line 49

def writeNote(midiNote, noteLength, midiTrack)
    midiTrack.events << MIDI::NoteOnEvent.new(0, midiNote, 127, 0) 
    midiTrack.events << MIDI::NoteOffEvent.new(0, midiNote, 127, \
    @song.length_to_delta(noteLength))
end

#writeSeqToTrack(midiSeq, midiTrack) ⇒ Object

writes a note sequence generate by a RhythmParser to a midi track

Parameters:

  • midiSeq (Array<Array>)

    an array of [midiNote, noteLength] (created by RhythmParser)

  • midiTrack (MIDI:Track)

    target track, generated with ‘createTrack’. if a track is reused the event sequence will be appended



38
39
40
41
42
43
# File 'lib/rhythmruby/MidiWriter.rb', line 38

def writeSeqToTrack(midiSeq, midiTrack)
  midiSeq.each do
    |midiNote, noteLength|    
    writeNote(midiNote, noteLength, midiTrack)
  end
end

#writeToFile(fileName) ⇒ Object

write the midiSong to file consisting of all the created midiTracks

Parameters:

  • fileName (String)

    where the midiSong is written to, can be a path



57
58
59
# File 'lib/rhythmruby/MidiWriter.rb', line 57

def writeToFile(fileName)
  open(fileName, 'w') {|f| @song.write(f) }
end