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 Receiver receiver;
21 private static MidiChannel[] channels;
22 private static MidiChannel activeChannel;
23 private static MidiEvent[] timeSignatures, tempoChanges;
24 private static ArrayList emptyTracks;
25 private static Map trackMute = new HashMap();
26 private static Map trackSolo = new HashMap();
29 private static String filename;
30 private static long editPosition;
31 private static boolean makeGUI = true, isEdited = false, drawEmptyTracks = false;
32 private static Thread player;
33 public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
36 * Starts the application.
38 * Parses command-line arguments, acquires MIDI devices and connects them,
39 * loads a sequence and creates the GUI.
41 public static void main (String[] args) {
42 System.out.println("\nMoosique version 1.0\n");
44 // Parses command-line arguments.
45 String fileArg = null;
46 for (int i = 0; i < args.length; i++) {
47 if (args[i].equals("-n")) {makeGUI = false;}
48 else if (fileArg == null) {fileArg = args[i];}
51 // Acquires MIDI devices and connects them.
52 System.out.print("Initializing MIDI devices.");
54 sequencer = MidiSystem.getSequencer();
55 System.out.print(".");
57 synthesizer = MidiSystem.getSynthesizer();
58 System.out.print(".");
60 receiver = synthesizer.getReceiver();
61 sequencer.getTransmitter().setReceiver(receiver);
62 channels = synthesizer.getChannels();
64 } catch (MidiUnavailableException e) {
65 System.out.println("Failed, quitting.");
68 System.out.println("Done");
70 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
71 if (fileArg != null) {
72 System.out.print("Loading MIDI sequence from " + fileArg + "...");
74 System.out.println("Failed, creating new sequence");
77 System.out.println("Done");
80 // Otherwise creates a new empty one.
84 // Builds GUI, unless n-flag is set.
86 System.out.print("Building GUI.");
88 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
89 } catch (Exception e) {}
90 gui = new MooGUI(seq);
91 System.out.println("Done");
93 System.out.print("Playing...");
95 while (sequencer.isRunning()) {}
96 System.out.println("Done");
109 ** ACCESSOR METHODS **
120 * Returns the currently active MidiChannel.
121 * @return the active MidiChannel
123 public static MidiChannel getActiveChannel() {
124 return activeChannel;
128 * Returns the MidiChannels of the selected synthesizer.
129 * @return the available MidiChannels
131 public static MidiChannel getChannel(int i) {
136 * Returns the MidiChannels of the selected synthesizer.
137 * @return the available MidiChannels
139 public static MidiChannel[] getChannels() {
144 * Returns the current editing position of the sequencer.
145 * @return the tick position
147 public static long getEditPosition() {
155 public static MooGUI getGUI() {
160 * Returns the receiver of the current sequencer.
161 * @return the receiver
163 public static Receiver getReceiver() {
168 * Returns the current sequence.
169 * @return the current sequence
171 public static Sequence getSequence() {
176 * Returns the current sequencer.
177 * @return the current sequencer
179 public static Sequencer getSequencer() {
184 * Returns the tempo of the current sequence.
185 * @return the tick position
187 public static int getTempo() {
189 // if (tempoMsg == null) return 0;
193 * Returns the tempo of the current sequence.
194 * @return the tick position
196 public static int[] getTimeSig() {
199 // if (timeSigMsg == null) return 0;
203 * Returns true if the current sequence has been edited.
204 * @return the tick position
206 public static boolean isEdited() {
211 * Returns whether the given track should be drawn
212 * @return true if the given track should be drawn
214 public static boolean shouldBeDrawn(Track track) {
215 if (drawEmptyTracks) return true;
216 else return (!emptyTracks.contains(track));
227 ** MUTATOR METHODS **
238 * Fast forwards the current sequence the given number of measures.
239 * @param measures the number of measures to fast forward
241 public static void forward(long ticks) {
242 editPosition += ticks;
246 * Rewinds the current sequence the given number of measures.
247 * @param measures the number of measures to rewind
249 public static void rewind(long ticks) {
250 editPosition -= ticks;
254 * Sets the currently active MidiChannel.
255 * @param channel the number of the MidiChannel to activate
257 public static void setActiveChannel(int channel) {
258 activeChannel = channels[channel];
262 * Sets whether empty tracks should be drawn
263 * @param state true if empty tracks should be drawn
265 public static void setDrawEmptyTracks(boolean state) {
266 drawEmptyTracks = state;
270 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
272 public static void setEdited() {
277 * Sets the current editing position of the sequencer.
278 * @param ticks the tick position
280 public static void setEditPosition(long ticks) {
281 editPosition = ticks;
285 * Sets the current editing position of the sequencer.
286 * @param ticks the tick position
288 public static void setTempo(int bpm) {
293 * Sets the current editing position of the sequencer.
294 * @param ticks the tick position
296 public static void setTimeSig(int bpm) {
308 ** PLAYBACK METHODS **
319 * Starts playback of the current sequence.
321 public static void play() {
322 sequencer.setTickPosition(editPosition);
327 * Resumes playback of the current sequence.
329 public static void resume() {
332 sequencer.setSequence(seq);
333 } catch (InvalidMidiDataException e) {}
334 Track[] tracks = seq.getTracks();
336 for (int i = 0; i < tracks.length; i++) {
338 Object ob = trackSolo.get(tracks[i]);
339 if(ob instanceof Boolean){
340 System.out.println("Track solo " + i + "= "+ ob);
341 sequencer.setTrackSolo(i,((Boolean)ob).booleanValue());
344 ob = trackMute.get(tracks[i]);
345 if(ob instanceof Boolean){
346 System.out.println("Track mute " + i + "= "+ ob);
347 sequencer.setTrackMute(i,((Boolean)ob).booleanValue());
353 // Disables input to volatile components
356 // Creates the visualisation thread and starts it.
357 player = new Thread () {
359 while(sequencer.isRunning()) {
360 // Updates the GUI with the current tick position.
361 gui.update(sequencer.getTickPosition());
363 // Puts the thread to sleep for as long as it takes
364 // the sequencer to reach the next sixteenth.
366 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
368 } catch (InterruptedException e) {
379 * Pauses playback of the current sequence.
381 public static void pause() {
382 if (sequencer.isRunning()) {
385 if (player != null) player.interrupt();
389 * Stops playback of the current sequence.
391 public static void stop() {
392 if (sequencer.isRunning()) {
395 sequencer.setTickPosition(editPosition);
396 if (player != null) player.interrupt();
408 ** SYSTEM & IO METHODS **
419 * Replaces the current sequence with a new one, holding three empty tracks.
421 public static void clearSequence() {
422 // Creates a new sequence and sends it to the sequencer.
424 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
425 sequencer.setSequence(seq);
427 emptyTracks = new ArrayList();
428 } catch (InvalidMidiDataException e) {}
429 // Sends sequence to GUI.
430 if (gui != null) gui.setSequence(seq);
434 * Loads a MIDI sequence from the given file.
435 * @param filename the filename to use
437 public static boolean load(String file) {
438 // Loads sequence from file
441 seq = MidiSystem.getSequence(new File(filename));
442 } catch (InvalidMidiDataException e) {
444 } catch (IOException e) {
449 Track[] tracks = seq.getTracks();
450 emptyTracks = new ArrayList();
451 trackMute = new HashMap();
452 trackSolo = new HashMap();
454 // Searches track 0 for changes in tempo and time signature.
457 ArrayList ts = new ArrayList(), tc = new ArrayList();
458 for (int i = 0; i < tracks[0].size(); i++) {
459 event = tracks[0].get(i);
460 if (event.getMessage().getStatus() == MetaMessage.META) {
461 metaMsg = (MetaMessage)event.getMessage();
462 switch(metaMsg.getType()) {
463 case 81: tc.add(event); break;
464 case 88: ts.add(event);
468 // timeSignatures = ts.toArray(timeSignatures);
469 // tempoChanges = tc.toArray(tempoChanges);
471 // Wraps each NoteOn event with its NoteOff event in a MooNote
472 ArrayList noteOns, noteOffs;
473 for (int i = 0; i < tracks.length; i++) {
474 // Searches the sequence for NoteOn and NoteOff events
475 noteOns = new ArrayList(tracks[i].size() / 2);
476 noteOffs = new ArrayList(tracks[i].size() / 2);
477 for (int j = 0; j < tracks[i].size(); j++) {
478 event = tracks[i].get(j);
479 if (event.getMessage().getStatus() >= 144 &&
480 event.getMessage().getStatus() < 160) noteOns.add(event);
481 if (event.getMessage().getStatus() >= 128 &&
482 event.getMessage().getStatus() < 144) noteOffs.add(event);
484 noteOns.trimToSize();
485 noteOffs.trimToSize();
486 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
488 // Sorts the note lists by tick position.
489 Comparator c = new Comparator() {
490 public int compare(Object o1, Object o2) {
491 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
494 Collections.sort(noteOns, c);
495 Collections.sort(noteOffs, c);
497 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
498 Iterator iOn = noteOns.iterator(), iOff;
499 MidiEvent on, off = null, nextOff;
500 ShortMessage onMsg, nextOffMsg;
501 while(iOn.hasNext()) {
502 on = (MidiEvent)iOn.next();
503 onMsg = (ShortMessage)on.getMessage();
504 iOff = noteOffs.iterator();
505 while(iOff.hasNext()) {
506 nextOff = (MidiEvent)iOff.next();
507 nextOffMsg = (ShortMessage)nextOff.getMessage();
508 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
509 onMsg.getData1() == nextOffMsg.getData1() &&
510 c.compare(nextOff, on) > 0) {
517 tracks[i].remove(on);
519 tracks[i].add(new MooNote(on, off));
521 tracks[i].add(new MooNote(on));
526 // Sends sequence to GUI and sequencer, then returns
527 if (gui != null) gui.setSequence(seq);
529 sequencer.setSequence(seq);
530 } catch (InvalidMidiDataException e) {}
535 * Saves the current sequence to the previously given filename.
537 public static boolean save() {
538 if (filename == null) return false;
546 * Saves the current sequence to the given filename
547 * @param file the filename to use
549 public static boolean saveAs(String file) {
551 MidiSystem.write(seq, 1, new File(file));
553 gui.setStatus("Saved " + file);
555 } catch (IOException e) {
556 gui.setStatus("Failed in saving " + file);
562 * Releases all reserved devices and exits the program.
564 public static void quit() {
565 if (isEdited && gui != null) {
566 int exitOption = JOptionPane.showConfirmDialog(gui,
567 "The current sequence has been edited, but not saved.\nDo you wish to quit anyway?",
568 "File not saved - really quit?",
569 JOptionPane.OK_CANCEL_OPTION,
570 JOptionPane.WARNING_MESSAGE);
571 if (exitOption == JOptionPane.CANCEL_OPTION || exitOption == JOptionPane.CLOSED_OPTION) return;
573 if (sequencer.isOpen()) sequencer.close();
574 if (synthesizer.isOpen()) synthesizer.close();
578 public static void setTrackSolo(Track track, boolean on){
579 trackSolo.put(track, new Boolean(on));
582 public static void setTrackMute(Track track, boolean on){
583 trackMute.put(track, new Boolean(on));