1 import javax.sound.midi.*;
7 * Moosique - The MIDI Tracker
9 * Main class that handles initiation, IO and sound.
11 * @author Einar Pehrson
14 public class Moosique {
16 private static MooGUI gui;
17 private static Sequence seq;
18 private static Sequencer sequencer;
19 private static Synthesizer synthesizer;
20 private static MidiChannel[] channels;
21 private static MidiChannel activeChannel;
22 private static MidiEvent[] timeSignatures, tempoChanges;
24 private static String filename, fileArg;
25 private static long editPosition;
26 private static boolean makeGUI = true, isEdited;
27 private static Thread player;
28 public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
31 * Starts the application.
33 public static void main (String[] args) {
34 System.out.println("\nMoosique version 1.0\n");
36 // Parses command-line arguments.
37 for (int i = 0; i < args.length; i++) {
38 if (args[i].equals("-n")) {makeGUI = false;}
39 else if (fileArg == null) {fileArg = args[i];}
42 // Acquires MIDI devices and connects them.
43 System.out.print("Initializing MIDI devices.");
45 sequencer = MidiSystem.getSequencer();
46 System.out.print(".");
48 synthesizer = MidiSystem.getSynthesizer();
49 System.out.print(".");
51 sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
52 channels = synthesizer.getChannels();
54 } catch (MidiUnavailableException e) {
55 System.out.println("Failed, quitting.");
58 System.out.println("Done");
60 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
61 if (fileArg != null) {
62 System.out.print("Loading MIDI sequence from " + fileArg + "...");
64 System.out.println("Failed");
67 System.out.println("Done");
70 // Otherwise creates a new empty one.
74 // Builds GUI, unless n-flag is set.
76 System.out.print("Building GUI...");
78 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
79 } catch (Exception e) {}
80 gui = new MooGUI(seq);
81 System.out.println("Done");
83 System.out.print("Playing...");
85 while (sequencer.isRunning()) {}
86 System.out.println("Done");
95 public static MooGUI getGUI() {
100 * Returns the current sequence.
101 * @return the current sequence
103 public static Sequence getSequence() {
108 * Returns the current sequencer.
109 * @return the current sequencer
111 public static Sequencer getSequencer() {
116 * Returns the MidiChannels of the selected synthesizer.
117 * @return the available MidiChannels
119 public static MidiChannel[] getChannels() {
124 * Returns the MidiChannels of the selected synthesizer.
125 * @return the available MidiChannels
127 public static MidiChannel getChannel(int i) {
132 * Returns the currently active MidiChannel.
133 * @return the active MidiChannel
135 public static MidiChannel getActiveChannel() {
136 return activeChannel;
140 * Sets the currently active MidiChannel.
141 * @param channel the number of the MidiChannel to activate
143 public static void setActiveChannel(int channel) {
144 activeChannel = channels[channel];
148 * Replaces the current sequence with a new one, holding three empty tracks.
150 public static void clearSequence() {
151 // Creates a new sequence and sends it to the sequencer.
153 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
154 sequencer.setSequence(seq);
155 } catch (InvalidMidiDataException e) {}
156 // Sends sequence to GUI.
157 if (gui != null) gui.setSequence(seq);
161 * Starts playback of the current sequence.
163 public static void play() {
164 sequencer.setTickPosition(editPosition);
169 * Pauses playback of the current sequence.
171 public static void pause() {
172 if (sequencer.isRunning()) {
175 if (player != null) player.interrupt();
179 * Resumes playback of the current sequence.
181 public static void resume() {
185 // Disables input to volatile components
188 // Creates the visualization thread and starts it.
189 player = new Thread () {
191 while(sequencer.isRunning()) {
192 // Updates the GUI with the current tick position.
193 gui.update(sequencer.getTickPosition());
195 // Puts the thread to sleep for as long as it takes
196 // the sequencer to reach the next sixteenth.
198 sleep((long)((1000 * 60 * 1) / (getTempo() * 4)));
199 } catch (InterruptedException e) {
210 * Stops playback of the current sequence.
212 public static void stop() {
213 if (sequencer.isRunning()) {
216 sequencer.setTickPosition(editPosition);
217 if (player != null) player.interrupt();
222 * Returns the current editing position of the sequencer.
223 * @return the tick position
225 public static long getPosition() {
230 * Sets the current editing position of the sequencer.
231 * @param ticks the tick position
233 public static void setPosition(long ticks) {
234 editPosition = ticks;
238 * Returns the tempo of the current sequence.
239 * @return the tick position
241 public static int getTempo() {
243 // if (tempoMsg == null) return 0;
247 * Sets the current editing position of the sequencer.
248 * @param ticks the tick position
250 public static void setTempo(int bpm) {
255 * Returns the tempo of the current sequence.
256 * @return the tick position
258 public static int[] getTimeSig() {
261 // if (timeSigMsg == null) return 0;
265 * Sets the current editing position of the sequencer.
266 * @param ticks the tick position
268 public static void setTimeSig(int bpm) {
273 * Returns true if the current sequence has been edited.
274 * @return the tick position
276 public static boolean isEdited() {
281 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
283 public static void setEdited() {
288 * Rewinds the current sequence the given number of measures.
289 * @param measures the number of measures to rewind
291 public static void rewind(long ticks) {
292 editPosition -= ticks;
296 * Fast forwards the current sequence the given number of measures.
297 * @param measures the number of measures to fast forward
299 public static void forward(long ticks) {
300 editPosition += ticks;
304 * Loads the MooSequence in the given file.
305 * @param filename the filename to use
307 public static boolean load(String file) {
308 // Loads sequence from file
311 seq = MidiSystem.getSequence(new File(filename));
312 } catch (InvalidMidiDataException e) {
314 } catch (IOException e) {
319 Track[] tracks = seq.getTracks();
321 // Searches track 0 for changes in tempo and time signature.
324 ArrayList ts = new ArrayList(), tc = new ArrayList();
325 for (int i = 0; i < tracks[0].size(); i++) {
326 event = tracks[0].get(i);
327 if (event.getMessage().getStatus() == MetaMessage.META) {
328 metaMsg = (MetaMessage)event.getMessage();
329 switch(metaMsg.getType()) {
330 case 81: tc.add(event); break;
331 case 88: ts.add(event);
335 // timeSignatures = ts.toArray(timeSignatures);
336 // tempoChanges = tc.toArray(tempoChanges);
338 // Wraps each NoteOn event with its NoteOff event in a MooNote
339 ArrayList noteOns, noteOffs;
340 for (int i = 0; i < tracks.length; i++) {
341 // Searches the sequence for NoteOn and NoteOff events
342 noteOns = new ArrayList(tracks[i].size() / 2);
343 noteOffs = new ArrayList(tracks[i].size() / 2);
344 for (int j = 0; j < tracks[i].size(); j++) {
345 event = tracks[i].get(j);
346 if (event.getMessage().getStatus() >= 144 &&
347 event.getMessage().getStatus() < 160) noteOns.add(event);
348 if (event.getMessage().getStatus() >= 128 &&
349 event.getMessage().getStatus() < 144) noteOffs.add(event);
351 noteOns.trimToSize();
352 noteOffs.trimToSize();
354 // Sorts the note lists by tick position.
355 Comparator c = new Comparator() {
356 public int compare(Object o1, Object o2) {
357 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
360 Collections.sort(noteOns, c);
361 Collections.sort(noteOffs, c);
363 // For each NoteOn event, finds its NoteOff event and replaces it with a MooNote.
364 Iterator iOn = noteOns.iterator(), iOff;
365 MidiEvent on, off = null, nextOff;
366 ShortMessage onMsg, nextOffMsg;
367 while(iOn.hasNext()) {
368 on = (MidiEvent)iOn.next();
369 onMsg = (ShortMessage)on.getMessage();
370 iOff = noteOffs.iterator();
371 while(iOff.hasNext()) {
372 nextOff = (MidiEvent)iOff.next();
373 nextOffMsg = (ShortMessage)nextOff.getMessage();
374 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
375 onMsg.getData1() == nextOffMsg.getData1() &&
376 c.compare(nextOff, on) > 0) {
383 tracks[i].remove(on);
385 tracks[i].add(new MooNote(on, off));
387 tracks[i].add(new MooNote(on));
394 Collections.sort(track[i].events, new Comparator() {
395 public int compare(Object o1, Object o2) {
396 return ((MidiEvent)o2).getTick() - ((MidiEvent)o1).getTick();
400 // Searches the sequence for NoteOn events
401 MidiEvent noteOn, noteOff = null, nextEvent;
403 ShortMessage shortMsg;
405 for (int i = 0; i < tracks.length; i++) {
406 for (int j = 0; j < tracks[i].size(); j++) {
407 noteOn = tracks[i].get(j);
408 if (noteOn.getMessage().getStatus() == ShortMessage.NOTE_ON) {
409 // Finds the corresponding NoteOff event
410 for (int k = j + 1; k < tracks[i].size(); k++) {
411 nextEvent = tracks[i].get(k);
412 nextMsg = nextEvent.getMessage();
413 if (nextMsg instanceof ShortMessage) {
414 shortMsg = (ShortMessage) nextMsg;
415 if (shortMsg.getCommand() == ShortMessage.NOTE_OFF && shortMsg.getChannel() == ((ShortMessage)noteOn.getMessage()).getChannel() && shortMsg.getData1() == ((ShortMessage)noteOn.getMessage()).getData1()) {
421 // Replaces the NoteOn event with a MooNote, if possible with the corresponding NoteOff event
422 tracks[i].remove(noteOn);
423 if (noteOff != null) {
424 tracks[i].add(new MooNote(noteOn, noteOff));
426 tracks[i].add(new MooNote(noteOn));
432 // Sends sequence to GUI and sequencer, then returns
433 if (gui != null) gui.setSequence(seq);
435 sequencer.setSequence(seq);
436 } catch (InvalidMidiDataException e) {}
441 * Saves the current sequence to the given filename
442 * @param file the filename to use
444 public static void saveAs(String file) {
446 MidiSystem.write(seq, 1, new File(filename));
447 } catch (IOException e) {}
449 gui.setStatus("Saved " + file);
453 * Saves the current sequence to the previously given filename.
455 public static void save() {
460 * Releases all reserved devices and exits the program.
462 public static void quit() {
463 if (sequencer.isOpen()) sequencer.close();
464 if (synthesizer.isOpen()) synthesizer.close();