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;
24 private static Map trackMute;
25 private static Map trackSolo;
28 private static String filename;
29 private static long editPosition;
30 private static boolean makeGUI = true, isEdited = false, drawEmptyTracks = false;
31 private static Thread player;
32 public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
35 * Starts the application.
37 public static void main (String[] args) {
38 System.out.println("\nMoosique version 1.0\n");
40 // Parses command-line arguments.
41 String fileArg = null;
42 for (int i = 0; i < args.length; i++) {
43 if (args[i].equals("-n")) {makeGUI = false;}
44 else if (fileArg == null) {fileArg = args[i];}
47 // Acquires MIDI devices and connects them.
48 System.out.print("Initializing MIDI devices.");
50 sequencer = MidiSystem.getSequencer();
51 System.out.print(".");
53 synthesizer = MidiSystem.getSynthesizer();
54 System.out.print(".");
56 sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
57 channels = synthesizer.getChannels();
59 } catch (MidiUnavailableException e) {
60 System.out.println("Failed, quitting.");
62 System.out.println("Done");
64 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
65 if (fileArg != null) {
66 System.out.print("Loading MIDI sequence from " + fileArg + "...");
68 System.out.println("Failed, creating new sequence");
71 System.out.println("Done");
74 // Otherwise creates a new empty one.
78 // Builds GUI, unless n-flag is set.
80 System.out.print("Building GUI.");
82 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
83 } catch (Exception e) {}
84 gui = new MooGUI(seq);
85 System.out.println("Done");
87 System.out.print("Playing...");
89 while (sequencer.isRunning()) {}
90 System.out.println("Done");
99 public static MooGUI getGUI() {
104 * Returns the current sequence.
105 * @return the current sequence
107 public static Sequence getSequence() {
112 * Returns the current sequencer.
113 * @return the current sequencer
115 public static Sequencer getSequencer() {
120 * Returns the MidiChannels of the selected synthesizer.
121 * @return the available MidiChannels
123 public static MidiChannel[] getChannels() {
128 * Returns the MidiChannels of the selected synthesizer.
129 * @return the available MidiChannels
131 public static MidiChannel getChannel(int i) {
136 * Returns the currently active MidiChannel.
137 * @return the active MidiChannel
139 public static MidiChannel getActiveChannel() {
140 return activeChannel;
144 * Sets the currently active MidiChannel.
145 * @param channel the number of the MidiChannel to activate
147 public static void setActiveChannel(int channel) {
148 activeChannel = channels[channel];
152 * Replaces the current sequence with a new one, holding three empty tracks.
154 public static void clearSequence() {
155 // Creates a new sequence and sends it to the sequencer.
157 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
158 sequencer.setSequence(seq);
160 emptyTracks = new ArrayList();
161 } catch (InvalidMidiDataException e) {}
162 // Sends sequence to GUI.
163 if (gui != null) gui.setSequence(seq);
167 * Starts playback of the current sequence.
169 public static void play() {
170 sequencer.setTickPosition(editPosition);
175 * Pauses playback of the current sequence.
177 public static void pause() {
178 if (sequencer.isRunning()) {
181 if (player != null) player.interrupt();
185 * Resumes playback of the current sequence.
187 public static void resume() {
190 sequencer.setSequence(seq);
191 } catch (InvalidMidiDataException e) {}
192 Track[] tracks = seq.getTracks();
194 for (int i = 0; i < tracks.length; i++) {
196 Object ob = trackSolo.get(tracks[i]);
197 if(ob instanceof Boolean){
198 System.out.println("Track solo " + i + "= "+ ob);
199 sequencer.setTrackSolo(i,((Boolean)ob).booleanValue());
202 ob = trackMute.get(tracks[i]);
203 if(ob instanceof Boolean){
204 System.out.println("Track mute " + i + "= "+ ob);
205 sequencer.setTrackMute(i,((Boolean)ob).booleanValue());
211 // Disables input to volatile components
214 // Creates the visualisation thread and starts it.
215 player = new Thread () {
217 while(sequencer.isRunning()) {
218 // Updates the GUI with the current tick position.
219 gui.update(sequencer.getTickPosition());
221 // Puts the thread to sleep for as long as it takes
222 // the sequencer to reach the next sixteenth.
224 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
226 } catch (InterruptedException e) {
237 * Stops playback of the current sequence.
239 public static void stop() {
240 if (sequencer.isRunning()) {
243 sequencer.setTickPosition(editPosition);
244 if (player != null) player.interrupt();
249 * Returns the current editing position of the sequencer.
250 * @return the tick position
252 public static long getEditPosition() {
257 * Sets the current editing position of the sequencer.
258 * @param ticks the tick position
260 public static void setEditPosition(long ticks) {
261 editPosition = ticks;
265 * Returns the tempo of the current sequence.
266 * @return the tick position
268 public static int getTempo() {
270 // if (tempoMsg == null) return 0;
274 * Sets the current editing position of the sequencer.
275 * @param ticks the tick position
277 public static void setTempo(int bpm) {
282 * Returns the tempo of the current sequence.
283 * @return the tick position
285 public static int[] getTimeSig() {
288 // if (timeSigMsg == null) return 0;
292 * Sets the current editing position of the sequencer.
293 * @param ticks the tick position
295 public static void setTimeSig(int bpm) {
300 * Returns true if the current sequence has been edited.
301 * @return the tick position
303 public static boolean isEdited() {
308 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
310 public static void setEdited() {
315 * Rewinds the current sequence the given number of measures.
316 * @param measures the number of measures to rewind
318 public static void rewind(long ticks) {
319 editPosition -= ticks;
323 * Fast forwards the current sequence the given number of measures.
324 * @param measures the number of measures to fast forward
326 public static void forward(long ticks) {
327 editPosition += ticks;
331 * Returns whether the given track should be drawn
332 * @return true if the given track should be drawn
334 public static boolean shouldBeDrawn(Track track) {
335 if (drawEmptyTracks) return true;
336 else return (!emptyTracks.contains(track));
341 * Sets whether empty tracks should be drawn
342 * @param state true if empty tracks should be drawn
344 public static void setDrawEmptyTracks(boolean state) {
345 drawEmptyTracks = state;
349 * Loads the MooSequence in the given file.
350 * @param filename the filename to use
352 public static boolean load(String file) {
353 // Loads sequence from file
356 seq = MidiSystem.getSequence(new File(filename));
357 } catch (InvalidMidiDataException e) {
359 } catch (IOException e) {
364 Track[] tracks = seq.getTracks();
365 emptyTracks = new ArrayList();
366 trackMute = new HashMap();
367 trackSolo = new HashMap();
369 // Searches track 0 for changes in tempo and time signature.
372 ArrayList ts = new ArrayList(), tc = new ArrayList();
373 for (int i = 0; i < tracks[0].size(); i++) {
374 event = tracks[0].get(i);
375 if (event.getMessage().getStatus() == MetaMessage.META) {
376 metaMsg = (MetaMessage)event.getMessage();
377 switch(metaMsg.getType()) {
378 case 81: tc.add(event); break;
379 case 88: ts.add(event);
383 // timeSignatures = ts.toArray(timeSignatures);
384 // tempoChanges = tc.toArray(tempoChanges);
386 // Wraps each NoteOn event with its NoteOff event in a MooNote
387 ArrayList noteOns, noteOffs;
388 for (int i = 0; i < tracks.length; i++) {
389 // Searches the sequence for NoteOn and NoteOff events
390 noteOns = new ArrayList(tracks[i].size() / 2);
391 noteOffs = new ArrayList(tracks[i].size() / 2);
392 for (int j = 0; j < tracks[i].size(); j++) {
393 event = tracks[i].get(j);
394 if (event.getMessage().getStatus() >= 144 &&
395 event.getMessage().getStatus() < 160) noteOns.add(event);
396 if (event.getMessage().getStatus() >= 128 &&
397 event.getMessage().getStatus() < 144) noteOffs.add(event);
399 noteOns.trimToSize();
400 noteOffs.trimToSize();
401 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
403 // Sorts the note lists by tick position.
404 Comparator c = new Comparator() {
405 public int compare(Object o1, Object o2) {
406 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
409 Collections.sort(noteOns, c);
410 Collections.sort(noteOffs, c);
412 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
413 Iterator iOn = noteOns.iterator(), iOff;
414 MidiEvent on, off = null, nextOff;
415 ShortMessage onMsg, nextOffMsg;
416 while(iOn.hasNext()) {
417 on = (MidiEvent)iOn.next();
418 onMsg = (ShortMessage)on.getMessage();
419 iOff = noteOffs.iterator();
420 while(iOff.hasNext()) {
421 nextOff = (MidiEvent)iOff.next();
422 nextOffMsg = (ShortMessage)nextOff.getMessage();
423 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
424 onMsg.getData1() == nextOffMsg.getData1() &&
425 c.compare(nextOff, on) > 0) {
432 tracks[i].remove(on);
434 tracks[i].add(new MooNote(on, off));
436 tracks[i].add(new MooNote(on));
441 // Sends sequence to GUI and sequencer, then returns
442 if (gui != null) gui.setSequence(seq);
444 sequencer.setSequence(seq);
445 } catch (InvalidMidiDataException e) {}
450 * Saves the current sequence to the given filename
451 * @param file the filename to use
453 public static boolean saveAs(String file) {
455 MidiSystem.write(seq, 1, new File(file));
457 gui.setStatus("Saved " + file);
459 } catch (IOException e) {
460 gui.setStatus("Failed in saving " + file);
466 * Saves the current sequence to the previously given filename.
468 public static boolean save() {
469 if (filename == null) return false;
477 * Releases all reserved devices and exits the program.
479 public static void quit() {
480 if (sequencer.isOpen()) sequencer.close();
481 if (synthesizer.isOpen()) synthesizer.close();
485 public static void setTrackSolo(Track track, boolean on){
486 trackSolo.put(track, new Boolean(on));
489 public static void setTrackMute(Track track, boolean on){
490 trackMute.put(track, new Boolean(on));