1 package com.jamesbryangraves.bob.midi;
2
3 import javax.sound.midi.InvalidMidiDataException;
4 import javax.sound.midi.MidiEvent;
5 import javax.sound.midi.MidiUnavailableException;
6 import javax.sound.midi.ShortMessage;
7
8 import org.apache.log4j.Logger;
9
10 import com.jamesbryangraves.bob.music.MusicEvent;
11 import com.jamesbryangraves.bob.music.MusicEventListener;
12
13 public class BobMidiSequencer implements MusicEventListener {
14
15 static Logger log = Logger.getLogger(BobMidiSequencer.class);
16
17 private BobMidiSequence sequence;
18 private long tickPosition;
19 private boolean open;
20
21 public BobMidiSequencer() {
22 tickPosition = 0;
23 }
24
25 public void open() throws MidiUnavailableException {
26 open = true;
27 if(sequence == null)
28 throw new MidiUnavailableException("Sequencer does not have a Sequence.");
29 }
30
31 public void start() {
32 while(isOpen()) {
33 for(BobMidiTrack track : sequence.getTracks()) {
34 for(MidiEvent e : track.getMidiEvents()) {
35 if(e.getTick() == tickPosition) {
36 track.getTransmitter().getReceiver().send(
37 e.getMessage(), System.currentTimeMillis());
38 track.remove(e);
39 }
40
41 }
42 }
43 try {
44 Thread.sleep((60000 / (long)sequence.getMusicContext().getBpm())
45 / sequence.getMusicContext().getTicksPerBeat());
46 } catch(InterruptedException ie) {
47 ie.printStackTrace();
48 }
49 tickPosition++;
50 }
51 }
52
53 public void stop() {
54
55 }
56
57 public void startRecording() {
58
59 }
60
61 public void stopRecording() {
62
63 }
64
65 public void handleMusicEvent(int index, MusicEvent event) {
66 try {
67 BobMidiTrack track = sequence.getTrack(index);
68 ShortMessage onMessage = new ShortMessage();
69 onMessage.setMessage(ShortMessage.NOTE_ON, track.getChannel(), event.getPitch(), 90);
70
71 track.add(new MidiEvent(onMessage, event.getTick()));
72 ShortMessage offMessage = new ShortMessage();
73 offMessage.setMessage(ShortMessage.NOTE_OFF, track.getChannel(), event.getPitch(), 90);
74
75 track.add(new MidiEvent(offMessage, event.getTick() + event.getValue()));
76 } catch(InvalidMidiDataException imde) {
77 System.err.println(imde.getMessage() + " event was: " +
78 "Track: " + index +
79 " Pitch: " + event.getPitch());
80 System.exit(1);
81 }
82
83 }
84
85 public BobMidiSequence getSequence() {
86 return sequence;
87 }
88
89 public void setSequence(BobMidiSequence sequence) {
90 this.sequence = sequence;
91 }
92
93 public long getTickPosition() {
94 return tickPosition;
95 }
96
97 public void setTickPosition(long tickPosition) {
98 this.tickPosition = tickPosition;
99 }
100
101 public boolean isOpen() {
102 return open;
103 }
104
105 public void setOpen(boolean open) {
106 this.open = open;
107 }
108 }