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;
23 private static ArrayList emptyTracks;
25 private static String filename, fileArg;
26 private static long editPosition;
27 private static boolean makeGUI = true, isEdited;
28 private static Thread player;
29 public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
32 * Starts the application.
34 public static void main (String[] args) {
35 System.out.println("\nMoosique version 1.0\n");
37 // Parses command-line arguments.
38 for (int i = 0; i < args.length; i++) {
39 if (args[i].equals("-n")) {makeGUI = false;}
40 else if (fileArg == null) {fileArg = args[i];}
43 // Acquires MIDI devices and connects them.
44 System.out.print("Initializing MIDI devices.");
46 sequencer = MidiSystem.getSequencer();
47 System.out.print(".");
49 synthesizer = MidiSystem.getSynthesizer();
50 System.out.print(".");
52 sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
53 channels = synthesizer.getChannels();
55 } catch (MidiUnavailableException e) {
56 System.out.println("Failed, quitting.");
59 System.out.println("Done");
61 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
62 if (fileArg != null) {
63 System.out.print("Loading MIDI sequence from " + fileArg + "...");
65 System.out.println("Failed");
68 System.out.println("Done");
71 // Otherwise creates a new empty one.
75 // Builds GUI, unless n-flag is set.
77 System.out.print("Building GUI...");
79 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
80 } catch (Exception e) {}
81 gui = new MooGUI(seq);
82 System.out.println("Done");
84 System.out.print("Playing...");
86 while (sequencer.isRunning()) {}
87 System.out.println("Done");
96 public static MooGUI getGUI() {
101 * Returns the current sequence.
102 * @return the current sequence
104 public static Sequence getSequence() {
109 * Returns the current sequencer.
110 * @return the current sequencer
112 public static Sequencer getSequencer() {
117 * Returns the MidiChannels of the selected synthesizer.
118 * @return the available MidiChannels
120 public static MidiChannel[] getChannels() {
125 * Returns the MidiChannels of the selected synthesizer.
126 * @return the available MidiChannels
128 public static MidiChannel getChannel(int i) {
133 * Returns the currently active MidiChannel.
134 * @return the active MidiChannel
136 public static MidiChannel getActiveChannel() {
137 return activeChannel;
141 * Sets the currently active MidiChannel.
142 * @param channel the number of the MidiChannel to activate
144 public static void setActiveChannel(int channel) {
145 activeChannel = channels[channel];
149 * Replaces the current sequence with a new one, holding three empty tracks.
151 public static void clearSequence() {
152 // Creates a new sequence and sends it to the sequencer.
154 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
155 sequencer.setSequence(seq);
156 } catch (InvalidMidiDataException e) {}
157 // Sends sequence to GUI.
158 if (gui != null) gui.setSequence(seq);
162 * Starts playback of the current sequence.
164 public static void play() {
165 sequencer.setTickPosition(editPosition);
170 * Pauses playback of the current sequence.
172 public static void pause() {
173 if (sequencer.isRunning()) {
176 if (player != null) player.interrupt();
180 * Resumes playback of the current sequence.
182 public static void resume() {
186 // Disables input to volatile components
189 // Creates the visualisation thread and starts it.
190 player = new Thread () {
192 long ticksPerSixteenth = seq.getResolution()/4;
193 System.out.println("Ticks/16: " + ticksPerSixteenth);
194 long position = sequencer.getTickPosition();
195 while(sequencer.isRunning()) {
196 long pos = sequencer.getTickPosition();
197 long tickDiff = pos - position;
198 System.out.print(" ... " + tickDiff);
201 // Updates the GUI with the current tick position.
202 gui.update(sequencer.getTickPosition());
204 // Puts the thread to sleep for as long as it takes
205 // the sequencer to reach the next sixteenth.
207 sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
208 } catch (InterruptedException e) {
219 * Stops playback of the current sequence.
221 public static void stop() {
222 if (sequencer.isRunning()) {
225 sequencer.setTickPosition(editPosition);
226 if (player != null) player.interrupt();
231 * Returns the current editing position of the sequencer.
232 * @return the tick position
234 public static long getEditPosition() {
239 * Sets the current editing position of the sequencer.
240 * @param ticks the tick position
242 public static void setEditPosition(long ticks) {
243 editPosition = ticks;
247 * Returns the tempo of the current sequence.
248 * @return the tick position
250 public static int getTempo() {
252 // if (tempoMsg == null) return 0;
256 * Sets the current editing position of the sequencer.
257 * @param ticks the tick position
259 public static void setTempo(int bpm) {
264 * Returns the tempo of the current sequence.
265 * @return the tick position
267 public static int[] getTimeSig() {
270 // if (timeSigMsg == null) return 0;
274 * Sets the current editing position of the sequencer.
275 * @param ticks the tick position
277 public static void setTimeSig(int bpm) {
282 * Returns true if the current sequence has been edited.
283 * @return the tick position
285 public static boolean isEdited() {
290 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
292 public static void setEdited() {
297 * Rewinds the current sequence the given number of measures.
298 * @param measures the number of measures to rewind
300 public static void rewind(long ticks) {
301 editPosition -= ticks;
305 * Fast forwards the current sequence the given number of measures.
306 * @param measures the number of measures to fast forward
308 public static void forward(long ticks) {
309 editPosition += ticks;
313 * Loads the MooSequence in the given file.
314 * @param filename the filename to use
316 public static boolean load(String file) {
317 // Loads sequence from file
320 seq = MidiSystem.getSequence(new File(filename));
321 } catch (InvalidMidiDataException e) {
323 } catch (IOException e) {
328 Track[] tracks = seq.getTracks();
329 emptyTracks = new ArrayList();
331 // Searches track 0 for changes in tempo and time signature.
334 ArrayList ts = new ArrayList(), tc = new ArrayList();
335 for (int i = 0; i < tracks[0].size(); i++) {
336 event = tracks[0].get(i);
337 if (event.getMessage().getStatus() == MetaMessage.META) {
338 metaMsg = (MetaMessage)event.getMessage();
339 switch(metaMsg.getType()) {
340 case 81: tc.add(event); break;
341 case 88: ts.add(event);
345 // timeSignatures = ts.toArray(timeSignatures);
346 // tempoChanges = tc.toArray(tempoChanges);
348 // Wraps each NoteOn event with its NoteOff event in a MooNote
349 ArrayList noteOns, noteOffs;
350 for (int i = 0; i < tracks.length; i++) {
351 // Searches the sequence for NoteOn and NoteOff events
352 noteOns = new ArrayList(tracks[i].size() / 2);
353 noteOffs = new ArrayList(tracks[i].size() / 2);
354 for (int j = 0; j < tracks[i].size(); j++) {
355 event = tracks[i].get(j);
356 if (event.getMessage().getStatus() >= 144 &&
357 event.getMessage().getStatus() < 160) noteOns.add(event);
358 if (event.getMessage().getStatus() >= 128 &&
359 event.getMessage().getStatus() < 144) noteOffs.add(event);
361 noteOns.trimToSize();
362 noteOffs.trimToSize();
363 boolean isEmpty = (noteOns.size() == 0);
364 String text = "Track " + i + " has " + noteOns.size() + "/" + noteOffs.size() + "/" + tracks[i].size();
365 if (isEmpty) text += " and will not be removed.";
366 System.out.println(text);
367 emptyTracks.add(tracks[i]);
369 // Sorts the note lists by tick position.
370 Comparator c = new Comparator() {
371 public int compare(Object o1, Object o2) {
372 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
375 Collections.sort(noteOns, c);
376 Collections.sort(noteOffs, c);
378 // For each NoteOn event, finds its NoteOff event and replaces it with a MooNote.
379 Iterator iOn = noteOns.iterator(), iOff;
380 MidiEvent on, off = null, nextOff;
381 ShortMessage onMsg, nextOffMsg;
382 while(iOn.hasNext()) {
383 on = (MidiEvent)iOn.next();
384 onMsg = (ShortMessage)on.getMessage();
385 iOff = noteOffs.iterator();
386 while(iOff.hasNext()) {
387 nextOff = (MidiEvent)iOff.next();
388 nextOffMsg = (ShortMessage)nextOff.getMessage();
389 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
390 onMsg.getData1() == nextOffMsg.getData1() &&
391 c.compare(nextOff, on) > 0) {
398 tracks[i].remove(on);
400 tracks[i].add(new MooNote(on, off));
402 tracks[i].add(new MooNote(on));
409 Collections.sort(track[i].events, new Comparator() {
410 public int compare(Object o1, Object o2) {
411 return ((MidiEvent)o2).getTick() - ((MidiEvent)o1).getTick();
415 // Searches the sequence for NoteOn events
416 MidiEvent noteOn, noteOff = null, nextEvent;
418 ShortMessage shortMsg;
420 for (int i = 0; i < tracks.length; i++) {
421 for (int j = 0; j < tracks[i].size(); j++) {
422 noteOn = tracks[i].get(j);
423 if (noteOn.getMessage().getStatus() == ShortMessage.NOTE_ON) {
424 // Finds the corresponding NoteOff event
425 for (int k = j + 1; k < tracks[i].size(); k++) {
426 nextEvent = tracks[i].get(k);
427 nextMsg = nextEvent.getMessage();
428 if (nextMsg instanceof ShortMessage) {
429 shortMsg = (ShortMessage) nextMsg;
430 if (shortMsg.getCommand() == ShortMessage.NOTE_OFF && shortMsg.getChannel() == ((ShortMessage)noteOn.getMessage()).getChannel() && shortMsg.getData1() == ((ShortMessage)noteOn.getMessage()).getData1()) {
436 // Replaces the NoteOn event with a MooNote, if possible with the corresponding NoteOff event
437 tracks[i].remove(noteOn);
438 if (noteOff != null) {
439 tracks[i].add(new MooNote(noteOn, noteOff));
441 tracks[i].add(new MooNote(noteOn));
447 // Sends sequence to GUI and sequencer, then returns
448 if (gui != null) gui.setSequence(seq);
450 sequencer.setSequence(seq);
451 } catch (InvalidMidiDataException e) {}
456 * Saves the current sequence to the given filename
457 * @param file the filename to use
459 public static void saveAs(String file) {
461 MidiSystem.write(seq, 1, new File(filename));
462 } catch (IOException e) {}
464 gui.setStatus("Saved " + file);
468 * Saves the current sequence to the previously given filename.
470 public static void save() {
475 * Releases all reserved devices and exits the program.
477 public static void quit() {
478 if (sequencer.isOpen()) sequencer.close();
479 if (synthesizer.isOpen()) synthesizer.close();