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();
338 for (int i = 0; i < tracks.length; i++) {
340 Object ob = trackSolo.get(tracks[i]);
341 if(ob instanceof Boolean){
342 sequencer.setTrackSolo(i,((Boolean)ob).booleanValue());
345 ob = trackMute.get(tracks[i]);
346 if(ob instanceof Boolean){
347 sequencer.setTrackMute(i,((Boolean)ob).booleanValue());
352 // Disables input to volatile components
355 // Creates the visualisation thread and starts it.
356 player = new Thread () {
358 while(sequencer.isRunning()) {
359 // Updates the GUI with the current tick position.
360 gui.update(sequencer.getTickPosition());
362 // Puts the thread to sleep for as long as it takes
363 // the sequencer to reach the next sixteenth.
365 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
367 } catch (InterruptedException e) {
378 * Pauses playback of the current sequence.
380 public static void pause() {
381 if (sequencer.isRunning()) {
384 if (player != null) player.interrupt();
388 * Stops playback of the current sequence.
390 public static void stop() {
391 if (sequencer.isRunning()) {
394 sequencer.setTickPosition(editPosition);
395 if (player != null) player.interrupt();
407 ** SYSTEM & IO METHODS **
418 * Replaces the current sequence with a new one, holding three empty tracks.
420 public static void clearSequence() {
421 // Creates a new sequence and sends it to the sequencer.
423 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
424 sequencer.setSequence(seq);
426 emptyTracks = new ArrayList();
427 trackSolo = new HashMap();
428 trackMute = new HashMap();
429 } catch (InvalidMidiDataException e) {}
430 // Sends sequence to GUI.
431 if (gui != null) gui.setSequence(seq);
435 * Loads a MIDI sequence from the given file.
436 * @param filename the filename to use
438 public static boolean load(String file) {
439 // Loads sequence from file
442 seq = MidiSystem.getSequence(new File(filename));
443 } catch (InvalidMidiDataException e) {
445 } catch (IOException e) {
450 Track[] tracks = seq.getTracks();
451 emptyTracks = new ArrayList();
452 trackMute = new HashMap();
453 trackSolo = new HashMap();
455 // Searches track 0 for changes in tempo and time signature.
458 ArrayList ts = new ArrayList(), tc = new ArrayList();
459 for (int i = 0; i < tracks[0].size(); i++) {
460 event = tracks[0].get(i);
461 if (event.getMessage().getStatus() == MetaMessage.META) {
462 metaMsg = (MetaMessage)event.getMessage();
463 switch(metaMsg.getType()) {
464 case 81: tc.add(event); break;
465 case 88: ts.add(event);
469 // timeSignatures = ts.toArray(timeSignatures);
470 // tempoChanges = tc.toArray(tempoChanges);
472 // Wraps each NoteOn event with its NoteOff event in a MooNote
473 ArrayList noteOns, noteOffs;
474 for (int i = 0; i < tracks.length; i++) {
475 // Searches the sequence for NoteOn and NoteOff events
476 noteOns = new ArrayList(tracks[i].size() / 2);
477 noteOffs = new ArrayList(tracks[i].size() / 2);
478 for (int j = 0; j < tracks[i].size(); j++) {
479 event = tracks[i].get(j);
480 if (event.getMessage().getStatus() >= 144 &&
481 event.getMessage().getStatus() < 160) noteOns.add(event);
482 if (event.getMessage().getStatus() >= 128 &&
483 event.getMessage().getStatus() < 144) noteOffs.add(event);
485 noteOns.trimToSize();
486 noteOffs.trimToSize();
487 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
489 // Sorts the note lists by tick position.
490 Comparator c = new Comparator() {
491 public int compare(Object o1, Object o2) {
492 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
495 Collections.sort(noteOns, c);
496 Collections.sort(noteOffs, c);
498 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
499 Iterator iOn = noteOns.iterator(), iOff;
500 MidiEvent on, off = null, nextOff;
501 ShortMessage onMsg, nextOffMsg;
502 while(iOn.hasNext()) {
503 on = (MidiEvent)iOn.next();
504 onMsg = (ShortMessage)on.getMessage();
505 iOff = noteOffs.iterator();
506 while(iOff.hasNext()) {
507 nextOff = (MidiEvent)iOff.next();
508 nextOffMsg = (ShortMessage)nextOff.getMessage();
509 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
510 onMsg.getData1() == nextOffMsg.getData1() &&
511 c.compare(nextOff, on) > 0) {
518 tracks[i].remove(on);
520 tracks[i].add(new MooNote(on, off));
522 tracks[i].add(new MooNote(on));
527 // Sends sequence to GUI and sequencer, then returns
528 if (gui != null) gui.setSequence(seq);
530 sequencer.setSequence(seq);
531 } catch (InvalidMidiDataException e) {}
536 * Saves the current sequence to the previously given filename.
538 public static boolean save() {
539 if (filename == null) return false;
547 * Saves the current sequence to the given filename
548 * @param file the filename to use
550 public static boolean saveAs(String file) {
552 MidiSystem.write(seq, 1, new File(file));
554 gui.setStatus("Saved " + file);
556 } catch (IOException e) {
557 gui.setStatus("Failed in saving " + file);
563 * Releases all reserved devices and exits the program.
565 public static void quit() {
566 if (isEdited && gui != null) {
567 int exitOption = JOptionPane.showConfirmDialog(gui,
568 "The current sequence has been edited, but not saved.\nDo you wish to quit anyway?",
569 "File not saved - really quit?",
570 JOptionPane.OK_CANCEL_OPTION,
571 JOptionPane.WARNING_MESSAGE);
572 if (exitOption == JOptionPane.CANCEL_OPTION || exitOption == JOptionPane.CLOSED_OPTION) return;
574 if (sequencer.isOpen()) sequencer.close();
575 if (synthesizer.isOpen()) synthesizer.close();
579 public static void setTrackSolo(Track track, boolean on){
580 trackSolo.put(track, new Boolean(on));
583 public static void setTrackMute(Track track, boolean on){
584 trackMute.put(track, new Boolean(on));