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;
25 private static String filename, fileArg;
26 private static long editPosition;
27 private static boolean makeGUI = true, isEdited = false, drawEmptyTracks = false;
28 private static Thread player;
29 public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
32 * Starts the application.
34 public static void main (String[] args) {
35 System.out.println("\nMoosique version 1.0\n");
37 // Parses command-line arguments.
38 for (int i = 0; i < args.length; i++) {
39 if (args[i].equals("-n")) {makeGUI = false;}
40 else if (fileArg == null) {fileArg = args[i];}
43 // Acquires MIDI devices and connects them.
44 System.out.print("Initializing MIDI devices.");
46 sequencer = MidiSystem.getSequencer();
47 System.out.print(".");
49 synthesizer = MidiSystem.getSynthesizer();
50 System.out.print(".");
52 sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
53 channels = synthesizer.getChannels();
55 } catch (MidiUnavailableException e) {
56 System.out.println("Failed, quitting.");
59 System.out.println("Done");
61 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
62 if (fileArg != null) {
63 System.out.print("Loading MIDI sequence from " + fileArg + "...");
65 System.out.println("Failed");
68 System.out.println("Done");
71 // Otherwise creates a new empty one.
75 // Builds GUI, unless n-flag is set.
77 System.out.print("Building GUI.");
79 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
80 } catch (Exception e) {}
81 gui = new MooGUI(seq);
82 System.out.println("Done");
84 System.out.print("Playing...");
86 while (sequencer.isRunning()) {}
87 System.out.println("Done");
96 public static MooGUI getGUI() {
101 * Returns the current sequence.
102 * @return the current sequence
104 public static Sequence getSequence() {
109 * Returns the current sequencer.
110 * @return the current sequencer
112 public static Sequencer getSequencer() {
117 * Returns the MidiChannels of the selected synthesizer.
118 * @return the available MidiChannels
120 public static MidiChannel[] getChannels() {
125 * Returns the MidiChannels of the selected synthesizer.
126 * @return the available MidiChannels
128 public static MidiChannel getChannel(int i) {
133 * Returns the currently active MidiChannel.
134 * @return the active MidiChannel
136 public static MidiChannel getActiveChannel() {
137 return activeChannel;
141 * Sets the currently active MidiChannel.
142 * @param channel the number of the MidiChannel to activate
144 public static void setActiveChannel(int channel) {
145 activeChannel = channels[channel];
149 * Replaces the current sequence with a new one, holding three empty tracks.
151 public static void clearSequence() {
152 // Creates a new sequence and sends it to the sequencer.
154 seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
155 sequencer.setSequence(seq);
156 emptyTracks = new ArrayList();
157 } catch (InvalidMidiDataException e) {}
158 // Sends sequence to GUI.
159 if (gui != null) gui.setSequence(seq);
163 * Starts playback of the current sequence.
165 public static void play() {
166 sequencer.setTickPosition(editPosition);
171 * Pauses playback of the current sequence.
173 public static void pause() {
174 if (sequencer.isRunning()) {
177 if (player != null) player.interrupt();
181 * Resumes playback of the current sequence.
183 public static void resume() {
186 sequencer.setSequence(seq);
187 } catch (InvalidMidiDataException e) {}
190 // Disables input to volatile components
193 // Creates the visualisation thread and starts it.
194 player = new Thread () {
196 long ticksPerSixteenth = seq.getResolution()/4;
197 System.out.println("Ticks/16: " + ticksPerSixteenth);
198 long position = sequencer.getTickPosition();
199 while(sequencer.isRunning()) {
200 long pos = sequencer.getTickPosition();
201 long tickDiff = pos - position;
202 System.out.print(" ... " + tickDiff);
205 // Updates the GUI with the current tick position.
206 gui.update(sequencer.getTickPosition());
208 // Puts the thread to sleep for as long as it takes
209 // the sequencer to reach the next sixteenth.
211 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
213 } catch (InterruptedException e) {
224 * Stops playback of the current sequence.
226 public static void stop() {
227 if (sequencer.isRunning()) {
230 sequencer.setTickPosition(editPosition);
231 if (player != null) player.interrupt();
236 * Returns the current editing position of the sequencer.
237 * @return the tick position
239 public static long getEditPosition() {
244 * Sets the current editing position of the sequencer.
245 * @param ticks the tick position
247 public static void setEditPosition(long ticks) {
248 editPosition = ticks;
252 * Returns the tempo of the current sequence.
253 * @return the tick position
255 public static int getTempo() {
257 // if (tempoMsg == null) return 0;
261 * Sets the current editing position of the sequencer.
262 * @param ticks the tick position
264 public static void setTempo(int bpm) {
269 * Returns the tempo of the current sequence.
270 * @return the tick position
272 public static int[] getTimeSig() {
275 // if (timeSigMsg == null) return 0;
279 * Sets the current editing position of the sequencer.
280 * @param ticks the tick position
282 public static void setTimeSig(int bpm) {
287 * Returns true if the current sequence has been edited.
288 * @return the tick position
290 public static boolean isEdited() {
295 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
297 public static void setEdited() {
302 * Rewinds the current sequence the given number of measures.
303 * @param measures the number of measures to rewind
305 public static void rewind(long ticks) {
306 editPosition -= ticks;
310 * Fast forwards the current sequence the given number of measures.
311 * @param measures the number of measures to fast forward
313 public static void forward(long ticks) {
314 editPosition += ticks;
318 * Returns whether the given track should be drawn
319 * @return true if the given track should be drawn
321 public static boolean shouldBeDrawn(Track track) {
322 if (drawEmptyTracks) return true;
323 else return (!emptyTracks.contains(track));
328 * Sets whether empty tracks should be drawn
329 * @param state true if empty tracks should be drawn
331 public static void setDrawEmptyTracks(boolean state) {
332 drawEmptyTracks = state;
336 * Loads the MooSequence in the given file.
337 * @param filename the filename to use
339 public static boolean load(String file) {
340 // Loads sequence from file
343 seq = MidiSystem.getSequence(new File(filename));
344 } catch (InvalidMidiDataException e) {
346 } catch (IOException e) {
351 Track[] tracks = seq.getTracks();
352 emptyTracks = new ArrayList();
354 // Searches track 0 for changes in tempo and time signature.
357 ArrayList ts = new ArrayList(), tc = new ArrayList();
358 for (int i = 0; i < tracks[0].size(); i++) {
359 event = tracks[0].get(i);
360 if (event.getMessage().getStatus() == MetaMessage.META) {
361 metaMsg = (MetaMessage)event.getMessage();
362 switch(metaMsg.getType()) {
363 case 81: tc.add(event); break;
364 case 88: ts.add(event);
368 // timeSignatures = ts.toArray(timeSignatures);
369 // tempoChanges = tc.toArray(tempoChanges);
371 // Wraps each NoteOn event with its NoteOff event in a MooNote
372 ArrayList noteOns, noteOffs;
373 for (int i = 0; i < tracks.length; i++) {
374 // Searches the sequence for NoteOn and NoteOff events
375 noteOns = new ArrayList(tracks[i].size() / 2);
376 noteOffs = new ArrayList(tracks[i].size() / 2);
377 for (int j = 0; j < tracks[i].size(); j++) {
378 event = tracks[i].get(j);
379 if (event.getMessage().getStatus() >= 144 &&
380 event.getMessage().getStatus() < 160) noteOns.add(event);
381 if (event.getMessage().getStatus() >= 128 &&
382 event.getMessage().getStatus() < 144) noteOffs.add(event);
384 noteOns.trimToSize();
385 noteOffs.trimToSize();
386 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
388 // Sorts the note lists by tick position.
389 Comparator c = new Comparator() {
390 public int compare(Object o1, Object o2) {
391 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
394 Collections.sort(noteOns, c);
395 Collections.sort(noteOffs, c);
397 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
398 Iterator iOn = noteOns.iterator(), iOff;
399 MidiEvent on, off = null, nextOff;
400 ShortMessage onMsg, nextOffMsg;
401 while(iOn.hasNext()) {
402 on = (MidiEvent)iOn.next();
403 onMsg = (ShortMessage)on.getMessage();
404 iOff = noteOffs.iterator();
405 while(iOff.hasNext()) {
406 nextOff = (MidiEvent)iOff.next();
407 nextOffMsg = (ShortMessage)nextOff.getMessage();
408 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
409 onMsg.getData1() == nextOffMsg.getData1() &&
410 c.compare(nextOff, on) > 0) {
417 tracks[i].remove(on);
419 tracks[i].add(new MooNote(on, off));
421 tracks[i].add(new MooNote(on));
426 // Sends sequence to GUI and sequencer, then returns
427 if (gui != null) gui.setSequence(seq);
429 sequencer.setSequence(seq);
430 } catch (InvalidMidiDataException e) {}
435 * Saves the current sequence to the given filename
436 * @param file the filename to use
438 public static void saveAs(String file) {
440 MidiSystem.write(seq, 1, new File(filename));
441 } catch (IOException e) {}
443 gui.setStatus("Saved " + file);
447 * Saves the current sequence to the previously given filename.
449 public static void save() {
454 * Releases all reserved devices and exits the program.
456 public static void quit() {
457 if (sequencer.isOpen()) sequencer.close();
458 if (synthesizer.isOpen()) synthesizer.close();