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;
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 String fileArg = null;
39 for (int i = 0; i < args.length; i++) {
40 if (args[i].equals("-n")) {makeGUI = false;}
41 else if (fileArg == null) {fileArg = args[i];}
44 // Acquires MIDI devices and connects them.
45 System.out.print("Initializing MIDI devices.");
47 sequencer = MidiSystem.getSequencer();
48 System.out.print(".");
50 synthesizer = MidiSystem.getSynthesizer();
51 System.out.print(".");
53 sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
54 channels = synthesizer.getChannels();
56 } catch (MidiUnavailableException e) {
57 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, creating new sequence");
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);
157 emptyTracks = new ArrayList();
158 } catch (InvalidMidiDataException e) {}
159 // Sends sequence to GUI.
160 if (gui != null) gui.setSequence(seq);
164 * Starts playback of the current sequence.
166 public static void play() {
167 sequencer.setTickPosition(editPosition);
172 * Pauses playback of the current sequence.
174 public static void pause() {
175 if (sequencer.isRunning()) {
178 if (player != null) player.interrupt();
182 * Resumes playback of the current sequence.
184 public static void resume() {
187 sequencer.setSequence(seq);
188 } catch (InvalidMidiDataException e) {}
191 // Disables input to volatile components
194 // Creates the visualisation thread and starts it.
195 player = new Thread () {
197 while(sequencer.isRunning()) {
198 // Updates the GUI with the current tick position.
199 gui.update(sequencer.getTickPosition());
201 // Puts the thread to sleep for as long as it takes
202 // the sequencer to reach the next sixteenth.
204 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
206 } catch (InterruptedException e) {
217 * Stops playback of the current sequence.
219 public static void stop() {
220 if (sequencer.isRunning()) {
223 sequencer.setTickPosition(editPosition);
224 if (player != null) player.interrupt();
229 * Returns the current editing position of the sequencer.
230 * @return the tick position
232 public static long getEditPosition() {
237 * Sets the current editing position of the sequencer.
238 * @param ticks the tick position
240 public static void setEditPosition(long ticks) {
241 editPosition = ticks;
245 * Returns the tempo of the current sequence.
246 * @return the tick position
248 public static int getTempo() {
250 // if (tempoMsg == null) return 0;
254 * Sets the current editing position of the sequencer.
255 * @param ticks the tick position
257 public static void setTempo(int bpm) {
262 * Returns the tempo of the current sequence.
263 * @return the tick position
265 public static int[] getTimeSig() {
268 // if (timeSigMsg == null) return 0;
272 * Sets the current editing position of the sequencer.
273 * @param ticks the tick position
275 public static void setTimeSig(int bpm) {
280 * Returns true if the current sequence has been edited.
281 * @return the tick position
283 public static boolean isEdited() {
288 * Sets the current sequence as edited, which implies prompts when loading a new sequence.
290 public static void setEdited() {
295 * Rewinds the current sequence the given number of measures.
296 * @param measures the number of measures to rewind
298 public static void rewind(long ticks) {
299 editPosition -= ticks;
303 * Fast forwards the current sequence the given number of measures.
304 * @param measures the number of measures to fast forward
306 public static void forward(long ticks) {
307 editPosition += ticks;
311 * Returns whether the given track should be drawn
312 * @return true if the given track should be drawn
314 public static boolean shouldBeDrawn(Track track) {
315 if (drawEmptyTracks) return true;
316 else return (!emptyTracks.contains(track));
321 * Sets whether empty tracks should be drawn
322 * @param state true if empty tracks should be drawn
324 public static void setDrawEmptyTracks(boolean state) {
325 drawEmptyTracks = state;
329 * Loads the MooSequence in the given file.
330 * @param filename the filename to use
332 public static boolean load(String file) {
333 // Loads sequence from file
336 seq = MidiSystem.getSequence(new File(filename));
337 } catch (InvalidMidiDataException e) {
339 } catch (IOException e) {
344 Track[] tracks = seq.getTracks();
345 emptyTracks = new ArrayList();
347 // Searches track 0 for changes in tempo and time signature.
350 ArrayList ts = new ArrayList(), tc = new ArrayList();
351 for (int i = 0; i < tracks[0].size(); i++) {
352 event = tracks[0].get(i);
353 if (event.getMessage().getStatus() == MetaMessage.META) {
354 metaMsg = (MetaMessage)event.getMessage();
355 switch(metaMsg.getType()) {
356 case 81: tc.add(event); break;
357 case 88: ts.add(event);
361 // timeSignatures = ts.toArray(timeSignatures);
362 // tempoChanges = tc.toArray(tempoChanges);
364 // Wraps each NoteOn event with its NoteOff event in a MooNote
365 ArrayList noteOns, noteOffs;
366 for (int i = 0; i < tracks.length; i++) {
367 // Searches the sequence for NoteOn and NoteOff events
368 noteOns = new ArrayList(tracks[i].size() / 2);
369 noteOffs = new ArrayList(tracks[i].size() / 2);
370 for (int j = 0; j < tracks[i].size(); j++) {
371 event = tracks[i].get(j);
372 if (event.getMessage().getStatus() >= 144 &&
373 event.getMessage().getStatus() < 160) noteOns.add(event);
374 if (event.getMessage().getStatus() >= 128 &&
375 event.getMessage().getStatus() < 144) noteOffs.add(event);
377 noteOns.trimToSize();
378 noteOffs.trimToSize();
379 if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
381 // Sorts the note lists by tick position.
382 Comparator c = new Comparator() {
383 public int compare(Object o1, Object o2) {
384 return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
387 Collections.sort(noteOns, c);
388 Collections.sort(noteOffs, c);
390 // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
391 Iterator iOn = noteOns.iterator(), iOff;
392 MidiEvent on, off = null, nextOff;
393 ShortMessage onMsg, nextOffMsg;
394 while(iOn.hasNext()) {
395 on = (MidiEvent)iOn.next();
396 onMsg = (ShortMessage)on.getMessage();
397 iOff = noteOffs.iterator();
398 while(iOff.hasNext()) {
399 nextOff = (MidiEvent)iOff.next();
400 nextOffMsg = (ShortMessage)nextOff.getMessage();
401 if(onMsg.getChannel() == nextOffMsg.getChannel() &&
402 onMsg.getData1() == nextOffMsg.getData1() &&
403 c.compare(nextOff, on) > 0) {
410 tracks[i].remove(on);
412 tracks[i].add(new MooNote(on, off));
414 tracks[i].add(new MooNote(on));
419 // Sends sequence to GUI and sequencer, then returns
420 if (gui != null) gui.setSequence(seq);
422 sequencer.setSequence(seq);
423 } catch (InvalidMidiDataException e) {}
428 * Saves the current sequence to the given filename
429 * @param file the filename to use
431 public static boolean saveAs(String file) {
433 MidiSystem.write(seq, 1, new File(file));
435 gui.setStatus("Saved " + file);
437 } catch (IOException e) {
438 gui.setStatus("Failed in saving " + file);
444 * Saves the current sequence to the previously given filename.
446 public static boolean save() {
447 if (filename == null) return false;
455 * Releases all reserved devices and exits the program.
457 public static void quit() {
458 if (sequencer.isOpen()) sequencer.close();
459 if (synthesizer.isOpen()) synthesizer.close();