Skip to content

Commit

Permalink
Make multiple instruments work
Browse files Browse the repository at this point in the history
Use separate tracks and channels. Thanks to Eric Floehr and Robin-Andrews for reporting. Closes #12.
  • Loading branch information
kroger committed Oct 4, 2015
1 parent 9698a2e commit aaafe96
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
22 changes: 22 additions & 0 deletions demo_tracks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from pyknon.genmidi import Midi
from pyknon.music import NoteSeq

# Notes on two tracks

notes1 = NoteSeq("C4.'' B8' A4 D")
notes2 = NoteSeq("E4 F G4. A8")

m = Midi(2, tempo=100, instrument=[12, 14])
m.seq_notes(notes1, track=0)
m.seq_notes(notes2, track=1)
m.write("tracks.mid")

# Chords on two tracks

chords1 = [NoteSeq("C2 E G"), NoteSeq("G2 B D")]
chords2 = [NoteSeq("C,4 E"), NoteSeq("E, G"), NoteSeq("G, B"), NoteSeq("B, D'")]

midi = Midi(2, tempo=60, instrument=[40, 20])
midi.seq_chords(chords1, track=0)
midi.seq_chords(chords2, track=1)
midi.write("chords.mid")
9 changes: 6 additions & 3 deletions pyknon/genmidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,23 @@ def __init__(self, number_tracks=1, tempo=60, instrument=0):
self.midi_data = MIDIFile(number_tracks)

for track in range(number_tracks):
channel = track
self.midi_data.addTrackName(track, 0, "Track {0}".format(track))
self.midi_data.addTempo(track, 0, tempo)
instr = instrument[track] if isinstance(instrument, list) else instrument
self.midi_data.addProgramChange(track, 0, 0, instr)
self.midi_data.addProgramChange(track, channel, 0, instr)

def seq_chords(self, seqlist, track=0, time=0):
if track + 1 > self.number_tracks:
raise MidiError("You are trying to use more tracks than we have.")

channel = track
for item in seqlist:
if isinstance(item, NoteSeq):
volume = item[0].volume
dur = item[0].midi_dur
for note in item:
self.midi_data.addNote(track, 0, note.midi_number, time, dur, volume)
self.midi_data.addNote(track, channel, note.midi_number, time, dur, volume)
time += dur
elif isinstance(item, Rest):
time += item.midi_dur
Expand All @@ -42,9 +44,10 @@ def seq_notes(self, noteseq, track=0, time=0):
if track + 1 > self.number_tracks:
raise MidiError("You are trying to use more tracks than we have.")

channel = track
for note in noteseq:
if isinstance(note, Note):
self.midi_data.addNote(track, 0, note.midi_number, time, note.midi_dur, note.volume)
self.midi_data.addNote(track, channel, note.midi_number, time, note.midi_dur, note.volume)
else:
# we ignore the rests
pass
Expand Down

0 comments on commit aaafe96

Please sign in to comment.