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;
25 private static ArrayList copyBuffer, emptyTracks;
26 private static Map trackMute = new HashMap();
27 private static Map trackSolo = new HashMap();
28 private static Thread player;
30 private static String filename;
31 private static long editPosition;
32 private static boolean makeGUI = true, initSound = true, edited = false, drawEmptyTracks = false;
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 (args[i].equals("-m")) initSound = false;
49 else if (fileArg == null) fileArg = args[i];
52 // Acquires MIDI devices and connects them.
53 System.out.print("Initializing MIDI devices.");
55 sequencer = MidiSystem.getSequencer();
56 System.out.print(".");
58 synthesizer = MidiSystem.getSynthesizer();
59 System.out.print(".");
61 receiver = synthesizer.getReceiver();
62 sequencer.getTransmitter().setReceiver(receiver);
63 channels = synthesizer.getChannels();
65 } catch (MidiUnavailableException e) {
66 System.out.println("Failed, quitting.");
69 System.out.println("Done");
71 // Loads user preferences (work directory, last opened files etc).
74 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
75 if (fileArg != null) {
76 System.out.print("Loading MIDI sequence from " + fileArg + "...");
78 System.out.println("Failed, creating new sequence");
81 System.out.println("Done");
84 // Otherwise creates a new empty one.
88 // Builds GUI, unless n-flag is set.
90 System.out.print("Building GUI.");
92 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
93 } catch (Exception e) {}
94 gui = new MooGUI(seq);
95 System.out.println("Done");
97 System.out.print("Playing...");
99 while (sequencer.isRunning()) {}
100 System.out.println("Done");
113 ** ACCESSOR METHODS **
124 * Returns the currently active MidiChannel.
125 * @return the active MidiChannel
127 public static MidiChannel getActiveChannel() {
128 return activeChannel;
132 * Returns the MidiChannels of the selected synthesizer.
133 * @return the available MidiChannels
135 public static MidiChannel getChannel(int i) {
140 * Returns the MidiChannels of the selected synthesizer.
141 * @return the available MidiChannels
143 public static MidiChannel[] getChannels() {
148 * Returns the current copy buffer.
149 * @return the current copy buffer
151 public static ArrayList getCopyBuffer() {
156 * Returns the current editing position of the sequencer.
157 * @return the tick position
159 public static long getEditPosition() {
167 public static MooGUI getGUI() {
172 * Calculates the position (measures, beats, ticks) in the current sequence for the given tick position.
173 * @return an array of integers where index 0 is measures, 1 is beats and 2 is ticks.
175 public static int[] getPositionForTick(long ticks) {
177 int measures, beats, ticks;
178 for (int i = 0; i < timeSignatures.length; i++) {
179 long tick = timeSignatures[i].getTick();
180 // Split the ticks in the interval into measures, beats and ticks.
183 int[] pos = {1, 1, 1};
188 * Returns the receiver of the current sequencer.
189 * @return the receiver
191 public static Receiver getReceiver() {
196 * Returns the current sequence.
197 * @return the current sequence
199 public static Sequence getSequence() {
204 * Returns the current sequencer.
205 * @return the current sequencer
207 public static Sequencer getSequencer() {
212 * Returns the tempo of the current sequence.
213 * @return the tick position
215 public static int getTempo() {
217 // if (tempoMsg == null) return 0;
221 * Calculates the tick position in the current sequence for the given position (measures, beats, ticks).
222 * @return the tick position.
224 public static long getTicksForPosition(int measures, int beats, int ticks) {
227 for (int i = 0; i < timeSignatures.length; i++) {
228 long tick = timeSignatures[i].getTick();
229 // Add the measures, beats and ticks in the interval.
236 * Returns the tempo of the current sequence.
237 * @return the tick position
239 public static int[] getTimeSig() {
242 // if (timeSigMsg == null) return 0;
246 * Returns true if the current sequence has been edited.
247 * @return the tick position
249 public static boolean isEdited() {
254 * Returns whether the given track should be drawn
255 * @return true if the given track should be drawn
257 public static boolean shouldBeDrawn(Track track) {
258 if (drawEmptyTracks) return true;
259 else return (!emptyTracks.contains(track));
270 ** MUTATOR METHODS **
281 * Fast forwards the current sequence the given number of measures.
282 * @param measures the number of measures to fast forward
284 public static void forward(long ticks) {
285 editPosition += ticks;
289 * Rewinds the current sequence the given number of measures.
290 * @param measures the number of measures to rewind
292 public static void rewind(long ticks) {
293 editPosition -= ticks;
297 * Sets the currently active MidiChannel.
298 * @param channel the number of the MidiChannel to activate
300 public static void setActiveChannel(int channel) {
301 activeChannel = channels[channel];
305 * Sets the current copy buffer.
306 * @param the copy buffer
308 public static void setCopyBuffer(ArrayList buffer) {
313 * Sets whether empty tracks should be drawn
314 * @param state true if empty tracks should be drawn
316 public static void setDrawEmptyTracks(boolean state) {
317 drawEmptyTracks = state;
321 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
323 public static void setEdited() {
328 * Sets the current editing position of the sequencer.
329 * @param ticks the tick position
331 public static void setEditPosition(long ticks) {
332 editPosition = ticks;
336 * Sets the current editing position of the sequencer.
337 * @param ticks the tick position
339 public static void setTempo(int bpm) {
344 * Sets the current editing position of the sequencer.
345 * @param ticks the tick position
347 public static void setTimeSig(int bpm) {
352 * Sets the solo setting of the given track.
353 * @param on true for solo, false for not
355 public static void setTrackSolo(Track track, boolean on){
356 trackSolo.put(track, new Boolean(on));
360 * Sets the mute setting of the given track.
361 * @param on true for mute, false for not
363 public static void setTrackMute(Track track, boolean on){
364 trackMute.put(track, new Boolean(on));
368 * Sets the current playback volume.
369 * @param volume the volume, between 0 and 1
371 public void setVolume(long volume) {
372 for (int i = 0; i < channels.length; i++) {
373 channels[i].controlChange(7, (int)(volume * 127.0));
385 ** PLAYBACK METHODS **
396 * Starts playback of the current sequence.
398 public static void play() {
399 sequencer.setTickPosition(editPosition);
404 * Resumes playback of the current sequence.
406 public static void resume() {
409 sequencer.setSequence(seq);
410 } catch (InvalidMidiDataException e) {}
411 Track[] tracks = seq.getTracks();
415 for (int i = 0; i < tracks.length; i++) {
417 Object ob = trackSolo.get(tracks[i]);
418 if(ob instanceof Boolean){
419 sequencer.setTrackSolo(i,((Boolean)ob).booleanValue());
422 ob = trackMute.get(tracks[i]);
423 if(ob instanceof Boolean){
424 sequencer.setTrackMute(i,((Boolean)ob).booleanValue());
429 // Disables input to volatile components
432 // Creates the visualisation thread and starts it.
433 player = new Thread () {
435 while(sequencer.isRunning()) {
436 // Updates the GUI with the current tick position.
437 gui.update(sequencer.getTickPosition());
439 // Puts the thread to sleep for as long as it takes
440 // the sequencer to reach the next sixteenth.
442 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
444 } catch (InterruptedException e) {
455 * Pauses playback of the current sequence.
457 public static void pause() {
458 if (sequencer.isRunning()) {
461 if (player != null) player.interrupt();
465 * Stops playback of the current sequence.
467 public static void stop() {
468 if (sequencer.isRunning()) {
471 sequencer.setTickPosition(editPosition);
472 if (player != null) player.interrupt();
484 ** SYSTEM & IO METHODS **
495 * Replaces the current sequence with a new one, holding three empty tracks.
497 public static void clearSequence() {
498 // Creates a new sequence and sends it to the sequencer.
500 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
501 sequencer.setSequence(seq);
503 emptyTracks = new ArrayList();
504 trackSolo = new HashMap();
505 trackMute = new HashMap();
506 copyBuffer = new ArrayList();
507 } catch (InvalidMidiDataException e) {}
508 // Sends sequence to GUI.
509 if (gui != null) gui.setSequence(seq);
513 * Wraps each NoteOn event in the track with its NoteOff event in a MooNote.
515 public static List convertTrack(Track track) {
516 // Searches the track for NoteOn and NoteOff events
517 ArrayList noteOns = new ArrayList(track.size() / 2);
518 ArrayList noteOffs = new ArrayList(track.size() / 2);
519 ArrayList mooNotes = new ArrayList();
521 for (int j = 0; j < track.size(); j++) {
522 event = track.get(j);
523 if (event.getMessage().getStatus() >= 144 &&
524 event.getMessage().getStatus() < 160) noteOns.add(event);
525 if (event.getMessage().getStatus() >= 128 &&
526 event.getMessage().getStatus() < 144) noteOffs.add(event);
528 noteOns.trimToSize();
529 noteOffs.trimToSize();
530 if (noteOns.size() == 0) emptyTracks.add(track);
532 // Sorts the note lists by tick position.
533 Comparator c = new MidiEventComparator();
534 Collections.sort(noteOns, c);
535 Collections.sort(noteOffs, c);
537 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
538 Iterator iOn = noteOns.iterator(), iOff;
539 MidiEvent on, off = null, nextOff;
540 ShortMessage onMsg, nextOffMsg;
541 while(iOn.hasNext()) {
542 on = (MidiEvent)iOn.next();
543 if (!(on instanceof MooNote)) {
544 onMsg = (ShortMessage)on.getMessage();
545 iOff = noteOffs.iterator();
546 while(iOff.hasNext()) {
547 nextOff = (MidiEvent)iOff.next();
548 nextOffMsg = (ShortMessage)nextOff.getMessage();
549 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
550 onMsg.getData1() == nextOffMsg.getData1() &&
551 c.compare(nextOff, on) > 0) {
561 mn = new MooNote(on, off);
563 mn = new MooNote(on, new MidiEvent((ShortMessage)on.getMessage().clone(), on.getTick() + 48));
574 * Loads a MIDI sequence from the given file.
575 * @param filename the filename to use
577 public static boolean load(String file) {
578 // Loads sequence from file
581 seq = MidiSystem.getSequence(new File(filename));
582 } catch (InvalidMidiDataException e) {
584 } catch (IOException e) {
589 Track[] tracks = seq.getTracks();
590 emptyTracks = new ArrayList();
591 trackMute = new HashMap();
592 trackSolo = new HashMap();
593 copyBuffer = new ArrayList();
595 // Searches track 0 for changes in tempo and time signature.
598 ArrayList ts = new ArrayList(), tc = new ArrayList();
599 for (int i = 0; i < tracks[0].size(); i++) {
600 event = tracks[0].get(i);
601 if (event.getMessage().getStatus() == MetaMessage.META) {
602 metaMsg = (MetaMessage)event.getMessage();
603 switch(metaMsg.getType()) {
604 case 81: tc.add(event); break;
605 case 88: ts.add(event);
609 // timeSignatures = ts.toArray(timeSignatures);
610 // tempoChanges = tc.toArray(tempoChanges);
613 for (int i = 0; i < tracks.length; i++) {
614 convertTrack(tracks[i]);
617 // Sends sequence to GUI and sequencer, then returns
618 if (gui != null) gui.setSequence(seq);
620 sequencer.setSequence(seq);
621 } catch (InvalidMidiDataException e) {}
626 * Loads the user preferences.
628 public static void loadPreferences() {
633 * Saves the user preferences.
635 public static void savePreferences() {
642 public static boolean promptOnUnsavedChanges() {
643 if (!edited) return false;
644 int exitOption = JOptionPane.showConfirmDialog(gui,
645 "The current sequence has been edited, but not saved.\nDo you wish to continue anyway?",
646 "File not saved - continue?",
647 JOptionPane.OK_CANCEL_OPTION,
648 JOptionPane.WARNING_MESSAGE);
649 if (exitOption == JOptionPane.CANCEL_OPTION || exitOption == JOptionPane.CLOSED_OPTION) return true;
654 * Saves the current sequence to the previously given filename.
656 public static boolean save() {
657 if (filename == null) return false;
665 * Saves the current sequence to the given filename
666 * @param file the filename to use
668 public static boolean saveAs(String file) {
670 MidiSystem.write(seq, 1, new File(file));
673 gui.setStatus("Saved " + file);
675 } catch (IOException e) {
676 gui.setStatus("Failed in saving " + file);
682 * Releases all reserved devices and exits the program.
684 public static void quit() {
686 if (promptOnUnsavedChanges()) return;
689 if (sequencer.isOpen()) sequencer.close();
690 if (synthesizer.isOpen()) synthesizer.close();
695 * A Comparator for sorting lists of MidiEvents.
697 public static class MidiEventComparator implements Comparator {
698 public int compare(Object o1, Object o2) {
699 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());