Class: Musa::MIDIRecorder::MIDIRecorder

Inherits:
Object
  • Object
show all
Defined in:
lib/musa-dsl/midi/midi-recorder.rb

Instance Method Summary collapse

Constructor Details

#initialize(sequencer) ⇒ MIDIRecorder

Returns a new instance of MIDIRecorder.



6
7
8
9
10
11
# File 'lib/musa-dsl/midi/midi-recorder.rb', line 6

def initialize(sequencer)
  @sequencer = sequencer
  @midi_parser = MIDIParser.new

  clear
end

Instance Method Details

#clearObject



13
14
15
# File 'lib/musa-dsl/midi/midi-recorder.rb', line 13

def clear
  @messages = []
end

#rawObject



26
27
28
# File 'lib/musa-dsl/midi/midi-recorder.rb', line 26

def raw
  @messages
end

#record(midi_bytes) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/musa-dsl/midi/midi-recorder.rb', line 17

def record(midi_bytes)
  m = @midi_parser.parse midi_bytes
  m = [m] unless m.is_a? Array

  m.each do |mm|
    @messages << Message.new(@sequencer.position, mm)
  end
end

#transcriptionObject



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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/musa-dsl/midi/midi-recorder.rb', line 30

def transcription
  note_on = {}
  last_note = {}

  notes = []

  @messages.each do |m|
    mm = m.message

    case mm
    when MIDIEvents::NoteOn
      if last_note[mm.channel]
        notes << { position: last_note[mm.channel], channel: mm.channel, pitch: :silence, duration: m.position - last_note[mm.channel] }
        last_note.delete mm.channel
      end

      note = { position: m.position, channel: mm.channel, pitch: mm.note, velocity: mm.velocity }

      note_on[mm.channel] ||= {}
      note_on[mm.channel][mm.note] = note

      notes << note

    when MIDIEvents::NoteOff
      note_on[mm.channel] ||= {}

      note = note_on[mm.channel][mm.note]

      if note
        note_on[mm.channel].delete mm.note

        note[:duration] = m.position - note[:position]
        note[:velocity_off] = mm.velocity
      end

      last_note[mm.channel] = m.position
    end
  end

  notes
end