Repository navigation
Expand file tree
/
Copy pathfrom_scratch.rb
More file actions
executable file
·49 lines (39 loc) · 1.64 KB
/
Copy pathfrom_scratch.rb
File metadata and controls
executable file
·49 lines (39 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
#! /usr/bin/env ruby
#
# usage: from_scratch.rb
#
# This script shows you how to create a new sequence from scratch and save it
# to a MIDI file. It creates a file called 'from_scratch.mid'.
require_relative '../lib/midilib/sequence'
require_relative '../lib/midilib/consts'
include MIDI
seq = Sequence.new
# Create a first track for the sequence. This holds tempo events and stuff
# like that.
track = Track.new(seq)
seq.tracks << track
track.events << Tempo.new(Tempo.bpm_to_mpq(120))
track.events << MetaEvent.new(META_SEQ_NAME, 'Sequence Name')
# Create a track to hold the notes. Add it to the sequence.
track = Track.new(seq)
seq.tracks << track
# Give the track a name and an instrument name (optional).
track.name = 'My New Track'
track.instrument = GM_PATCH_NAMES[0]
# Add a volume controller event (optional).
track.events << Controller.new(0, CC_VOLUME, 127)
# Add events to the track: a major scale. Arguments for note on and note off
# constructors are channel, note, velocity, and delta_time. Channel numbers
# start at zero. We use the new Sequence#note_to_delta method to get the
# delta time length of a single quarter note.
track.events << ProgramChange.new(0, 1, 0)
quarter_note_length = seq.note_to_delta('quarter')
[0, 2, 4, 5, 7, 9, 11, 12].each do |offset|
track.events << NoteOn.new(0, 64 + offset, 127, 0)
track.events << NoteOff.new(0, 64 + offset, 127, quarter_note_length)
end
# Calling recalc_times is not necessary, because that only sets the events'
# start times, which are not written out to the MIDI file. The delta times are
# what get written out.
# track.recalc_times
File.open('from_scratch.mid', 'wb') { |file| seq.write(file) }