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 Track[] tracks = seq.getTracks();
193 for (int i = 0; i < tracks.length; i++) {
195 Object ob = trackSolo.get(tracks[i]);
196 if(ob instanceof Boolean){
197 System.out.println("Track solo " + i + "= "+ ob);
198 sequencer.setTrackSolo(i,((Boolean)ob).booleanValue());
201 ob = trackMute.get(tracks[i]);
202 if(ob instanceof Boolean){
203 System.out.println("Track mute " + i + "= "+ ob);
204 sequencer.setTrackMute(i,((Boolean)ob).booleanValue());
207 } catch (InvalidMidiDataException e) {}
210 // Disables input to volatile components
213 // Creates the visualisation thread and starts it.
214 player = new Thread () {
216 while(sequencer.isRunning()) {
217 // Updates the GUI with the current tick position.
218 gui.update(sequencer.getTickPosition());
220 // Puts the thread to sleep for as long as it takes
221 // the sequencer to reach the next sixteenth.
223 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
225 } catch (InterruptedException e) {
236 * Stops playback of the current sequence.
238 public static void stop() {
239 if (sequencer.isRunning()) {
242 sequencer.setTickPosition(editPosition);
243 if (player != null) player.interrupt();
248 * Returns the current editing position of the sequencer.
249 * @return the tick position
251 public static long getEditPosition() {
256 * Sets the current editing position of the sequencer.
257 * @param ticks the tick position
259 public static void setEditPosition(long ticks) {
260 editPosition = ticks;
264 * Returns the tempo of the current sequence.
265 * @return the tick position
267 public static int getTempo() {
269 // if (tempoMsg == null) return 0;
273 * Sets the current editing position of the sequencer.
274 * @param ticks the tick position
276 public static void setTempo(int bpm) {
281 * Returns the tempo of the current sequence.
282 * @return the tick position
284 public static int[] getTimeSig() {
287 // if (timeSigMsg == null) return 0;
291 * Sets the current editing position of the sequencer.
292 * @param ticks the tick position
294 public static void setTimeSig(int bpm) {
299 * Returns true if the current sequence has been edited.
300 * @return the tick position
302 public static boolean isEdited() {
307 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
309 public static void setEdited() {
314 * Rewinds the current sequence the given number of measures.
315 * @param measures the number of measures to rewind
317 public static void rewind(long ticks) {
318 editPosition -= ticks;
322 * Fast forwards the current sequence the given number of measures.
323 * @param measures the number of measures to fast forward
325 public static void forward(long ticks) {
326 editPosition += ticks;
330 * Returns whether the given track should be drawn
331 * @return true if the given track should be drawn
333 public static boolean shouldBeDrawn(Track track) {
334 if (drawEmptyTracks) return true;
335 else return (!emptyTracks.contains(track));
340 * Sets whether empty tracks should be drawn
341 * @param state true if empty tracks should be drawn
343 public static void setDrawEmptyTracks(boolean state) {
344 drawEmptyTracks = state;
348 * Loads the MooSequence in the given file.
349 * @param filename the filename to use
351 public static boolean load(String file) {
352 // Loads sequence from file
355 seq = MidiSystem.getSequence(new File(filename));
356 } catch (InvalidMidiDataException e) {
358 } catch (IOException e) {
363 Track[] tracks = seq.getTracks();
364 emptyTracks = new ArrayList();
365 trackMute = new HashMap();
366 trackSolo = new HashMap();
368 // Searches track 0 for changes in tempo and time signature.
371 ArrayList ts = new ArrayList(), tc = new ArrayList();
372 for (int i = 0; i < tracks[0].size(); i++) {
373 event = tracks[0].get(i);
374 if (event.getMessage().getStatus() == MetaMessage.META) {
375 metaMsg = (MetaMessage)event.getMessage();
376 switch(metaMsg.getType()) {
377 case 81: tc.add(event); break;
378 case 88: ts.add(event);
382 // timeSignatures = ts.toArray(timeSignatures);
383 // tempoChanges = tc.toArray(tempoChanges);
385 // Wraps each NoteOn event with its NoteOff event in a MooNote
386 ArrayList noteOns, noteOffs;
387 for (int i = 0; i < tracks.length; i++) {
388 // Searches the sequence for NoteOn and NoteOff events
389 noteOns = new ArrayList(tracks[i].size() / 2);
390 noteOffs = new ArrayList(tracks[i].size() / 2);
391 for (int j = 0; j < tracks[i].size(); j++) {
392 event = tracks[i].get(j);
393 if (event.getMessage().getStatus() >= 144 &&
394 event.getMessage().getStatus() < 160) noteOns.add(event);
395 if (event.getMessage().getStatus() >= 128 &&
396 event.getMessage().getStatus() < 144) noteOffs.add(event);
398 noteOns.trimToSize();
399 noteOffs.trimToSize();
400 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
402 // Sorts the note lists by tick position.
403 Comparator c = new Comparator() {
404 public int compare(Object o1, Object o2) {
405 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
408 Collections.sort(noteOns, c);
409 Collections.sort(noteOffs, c);
411 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
412 Iterator iOn = noteOns.iterator(), iOff;
413 MidiEvent on, off = null, nextOff;
414 ShortMessage onMsg, nextOffMsg;
415 while(iOn.hasNext()) {
416 on = (MidiEvent)iOn.next();
417 onMsg = (ShortMessage)on.getMessage();
418 iOff = noteOffs.iterator();
419 while(iOff.hasNext()) {
420 nextOff = (MidiEvent)iOff.next();
421 nextOffMsg = (ShortMessage)nextOff.getMessage();
422 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
423 onMsg.getData1() == nextOffMsg.getData1() &&
424 c.compare(nextOff, on) > 0) {
431 tracks[i].remove(on);
433 tracks[i].add(new MooNote(on, off));
435 tracks[i].add(new MooNote(on));
440 // Sends sequence to GUI and sequencer, then returns
441 if (gui != null) gui.setSequence(seq);
443 sequencer.setSequence(seq);
444 } catch (InvalidMidiDataException e) {}
449 * Saves the current sequence to the given filename
450 * @param file the filename to use
452 public static boolean saveAs(String file) {
454 MidiSystem.write(seq, 1, new File(file));
456 gui.setStatus("Saved " + file);
458 } catch (IOException e) {
459 gui.setStatus("Failed in saving " + file);
465 * Saves the current sequence to the previously given filename.
467 public static boolean save() {
468 if (filename == null) return false;
476 * Releases all reserved devices and exits the program.
478 public static void quit() {
479 if (sequencer.isOpen()) sequencer.close();
480 if (synthesizer.isOpen()) synthesizer.close();
484 public static void setTrackSolo(Track track, boolean on){
485 trackSolo.put(track, new Boolean(on));
488 public static void setTrackMute(Track track, boolean on){
489 trackMute.put(track, new Boolean(on));