]> ruin.nu Git - moosique.git/blob - Moosique.java
moved it outside the try-catch block..
[moosique.git] / Moosique.java
1 import javax.sound.midi.*;
2 import java.io.*;
3 import javax.swing.*;
4 import java.util.*;
5
6 /**
7  * Moosique - The MIDI Tracker
8  * 
9  * Main class that handles initiation, IO and sound.
10  * 
11  * @author  Einar Pehrson
12  */
13  
14 public class Moosique {
15
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;
26
27
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;
33
34         /** 
35          * Starts the application.
36          */
37         public static void main (String[] args) {
38                 System.out.println("\nMoosique version 1.0\n");
39
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];}
45                 }
46
47                 // Acquires MIDI devices and connects them.
48                 System.out.print("Initializing MIDI devices.");
49                 try {
50                         sequencer = MidiSystem.getSequencer();
51                         System.out.print(".");
52                         sequencer.open();
53                         synthesizer = MidiSystem.getSynthesizer();
54                         System.out.print(".");
55                         synthesizer.open();
56                         sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
57                         channels = synthesizer.getChannels();
58                         setActiveChannel(0);
59                 } catch (MidiUnavailableException e) {
60                         System.out.println("Failed, quitting.");
61                 }
62                 System.out.println("Done");
63
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 + "...");
67                         if (!load(fileArg)) {
68                                 System.out.println("Failed, creating new sequence");
69                                 clearSequence();
70                         } else {
71                                 System.out.println("Done");
72                         }
73                 } else {
74                         // Otherwise creates a new empty one.
75                         clearSequence();
76                 }
77
78                 // Builds GUI, unless n-flag is set.
79                 if (makeGUI) {
80                         System.out.print("Building GUI.");
81                         try {
82                                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
83                         } catch (Exception e) {}
84                         gui = new MooGUI(seq);
85                         System.out.println("Done");
86                 } else {
87                         System.out.print("Playing...");
88                         play();
89                         while (sequencer.isRunning()) {}
90                         System.out.println("Done");
91                         quit();
92                 }
93         }
94
95         /** 
96          * Returns the GUI.
97          * @return the GUI
98          */
99         public static MooGUI getGUI() {
100                 return gui;
101         }
102
103         /** 
104          * Returns the current sequence.
105          * @return the current sequence
106          */
107         public static Sequence getSequence() {
108                 return seq;
109         }
110
111         /** 
112          * Returns the current sequencer.
113          * @return the current sequencer
114          */
115         public static Sequencer getSequencer() {
116                 return sequencer;
117         }
118
119         /** 
120          * Returns the MidiChannels of the selected synthesizer.
121          * @return the available MidiChannels
122          */
123         public static MidiChannel[] getChannels() {
124                 return channels;
125         }
126
127         /** 
128          * Returns the MidiChannels of the selected synthesizer.
129          * @return the available MidiChannels
130          */
131         public static MidiChannel getChannel(int i) {
132                 return channels[i];
133         }
134
135         /** 
136          * Returns the currently active MidiChannel.
137          * @return the active MidiChannel
138          */
139         public static MidiChannel getActiveChannel() {
140                 return activeChannel;
141         }
142
143         /** 
144          * Sets the currently active MidiChannel.
145          * @param channel       the number of the MidiChannel to activate
146          */
147         public static void setActiveChannel(int channel) {
148                 activeChannel = channels[channel];
149         }
150
151         /** 
152          * Replaces the current sequence with a new one, holding three empty tracks.
153          */
154         public static void clearSequence() {
155                 // Creates a new sequence and sends it to the sequencer.
156                 try {
157                         seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
158                         sequencer.setSequence(seq);
159                         filename = null;
160                         emptyTracks = new ArrayList();
161                 } catch (InvalidMidiDataException e) {}
162                 // Sends sequence to GUI.
163                 if (gui != null) gui.setSequence(seq);
164         }
165
166         /** 
167          * Starts playback of the current sequence.
168          */
169         public static void play() {
170                 sequencer.setTickPosition(editPosition);
171                 resume();
172         }
173
174         /** 
175          * Pauses playback of the current sequence.
176          */
177         public static void pause() {
178                 if (sequencer.isRunning()) {
179                         sequencer.stop();
180                 }
181                 if (player != null) player.interrupt();
182         }
183
184         /** 
185          * Resumes playback of the current sequence.
186          */
187         public static void resume() {
188                 gui.update(0);
189                 try {
190                         sequencer.setSequence(seq);
191                 } catch (InvalidMidiDataException e) {}
192                 Track[] tracks = seq.getTracks();
193
194                 for (int i = 0; i < tracks.length; i++) {
195
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());
200                         }
201
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());
206                         }
207                 }
208
209                 sequencer.start();
210
211                 // Disables input to volatile components
212                 // gui.disable();
213
214                 // Creates the visualisation thread and starts it.
215                 player = new Thread () {
216                         public void run() {
217                                 while(sequencer.isRunning()) {
218                                         // Updates the GUI with the current tick position.
219                                         gui.update(sequencer.getTickPosition());
220
221                                         // Puts the thread to sleep for as long as it takes
222                                         // the sequencer to reach the next sixteenth.
223                                         try {
224                                                 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
225                                                 sleep (10);
226                                         } catch (InterruptedException e) {
227                                                 Moosique.stop();
228                                         }
229                                 }
230                                 Moosique.stop();
231                         }
232                 };
233                 player.start();
234         }
235
236         /** 
237          * Stops playback of the current sequence.
238          */
239         public static void stop() {
240                 if (sequencer.isRunning()) {
241                         sequencer.stop();
242                 }
243                 sequencer.setTickPosition(editPosition);
244                 if (player != null) player.interrupt();
245                 gui.update((long)0);
246         }
247
248         /** 
249          * Returns the current editing position of the sequencer.
250          * @return the tick position
251          */
252         public static long getEditPosition() {
253                 return editPosition;
254         }
255
256         /** 
257          * Sets the current editing position of the sequencer.
258          * @param ticks         the tick position
259          */
260         public static void setEditPosition(long ticks) {
261                 editPosition = ticks;
262         }
263
264         /** 
265          * Returns the tempo of the current sequence.
266          * @return the tick position
267          */
268         public static int getTempo() {
269                 return 120;
270                 // if (tempoMsg == null) return 0;
271         }
272
273         /** 
274          * Sets the current editing position of the sequencer.
275          * @param ticks         the tick position
276          */
277         public static void setTempo(int bpm) {
278                 // tempoMsg
279         }
280
281         /** 
282          * Returns the tempo of the current sequence.
283          * @return the tick position
284          */
285         public static int[] getTimeSig() {
286                 int[] ts = {4, 4};
287                 return ts;
288                 // if (timeSigMsg == null) return 0;
289         }
290
291         /** 
292          * Sets the current editing position of the sequencer.
293          * @param ticks         the tick position
294          */
295         public static void setTimeSig(int bpm) {
296                 // timeSigMsg
297         }
298
299         /** 
300          * Returns true if the current sequence has been edited.
301          * @return the tick position
302          */
303         public static boolean isEdited() {
304                 return isEdited;
305         }
306
307         /** 
308          * Sets the current sequence as edited, which implies prompts when loading a new sequence.
309          */
310         public static void setEdited() {
311                 isEdited = true;
312         }
313
314         /** 
315          * Rewinds the current sequence the given number of measures.
316          * @param measures      the number of measures to rewind
317          */
318         public static void rewind(long ticks) {
319                 editPosition -= ticks;
320         }
321
322         /** 
323          * Fast forwards the current sequence the given number of measures.
324          * @param measures      the number of measures to fast forward
325          */
326         public static void forward(long ticks) {
327                 editPosition += ticks;
328         }
329
330         /** 
331          * Returns whether the given track should be drawn
332          * @return true if the given track should be drawn
333          */
334         public static boolean shouldBeDrawn(Track track) {
335                 if (drawEmptyTracks) return true;
336                 else return (!emptyTracks.contains(track));
337         }
338
339
340         /** 
341          * Sets whether empty tracks should be drawn
342          * @param state         true if empty tracks should be drawn
343          */
344         public static void setDrawEmptyTracks(boolean state) {
345                 drawEmptyTracks = state;
346         }
347
348         /** 
349          * Loads the MooSequence in the given file.
350          * @param filename      the filename to use
351          */
352         public static boolean load(String file) {
353                 // Loads sequence from file
354                 filename = file;
355                 try {
356                         seq = MidiSystem.getSequence(new File(filename));
357                 } catch (InvalidMidiDataException e) {
358                         return false;
359                 } catch (IOException e) {
360                         return false;
361                 }
362                 isEdited = false;
363
364                 Track[] tracks = seq.getTracks();
365                 emptyTracks = new ArrayList();
366                 trackMute = new HashMap();
367                 trackSolo = new HashMap();
368
369                 // Searches track 0 for changes in tempo and time signature.
370                 MidiEvent event;
371                 MetaMessage metaMsg;
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);
380                                 }
381                         }
382                 }
383 //              timeSignatures = ts.toArray(timeSignatures);
384 //              tempoChanges = tc.toArray(tempoChanges);
385
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);
398                         }
399                         noteOns.trimToSize();
400                         noteOffs.trimToSize();
401                         if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
402                         
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());
407                                 }
408                         };
409                         Collections.sort(noteOns, c);
410                         Collections.sort(noteOffs, c);
411
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) {
426                                                 off = nextOff;
427                                                 iOff.remove();
428                                                 break;
429                                         }
430                                                 
431                                 }
432                                 tracks[i].remove(on);
433                                 if (off != null) {
434                                         tracks[i].add(new MooNote(on, off));
435                                 } else {
436                                         tracks[i].add(new MooNote(on));
437                                 }
438                                 iOn.remove();
439                         }
440                 }
441                 // Sends sequence to GUI and sequencer, then returns
442                 if (gui != null) gui.setSequence(seq);
443                 try {
444                         sequencer.setSequence(seq);
445                 } catch (InvalidMidiDataException e) {}
446                 return true;
447         }
448
449         /** 
450          * Saves the current sequence to the given filename
451          * @param file  the filename to use
452          */
453         public static boolean saveAs(String file) {
454                 try {
455                         MidiSystem.write(seq, 1, new File(file));
456                         filename = file;
457                         gui.setStatus("Saved " + file);
458                         return true;
459                 } catch (IOException e) {
460                         gui.setStatus("Failed in saving " + file);
461                         return false;
462                 }
463         }
464
465         /** 
466          * Saves the current sequence to the previously given filename.
467          */
468         public static boolean save() {
469                 if (filename == null) return false;
470                 else {
471                         saveAs(filename);
472                         return true;
473                 }
474         }
475
476         /** 
477          * Releases all reserved devices and exits the program.
478          */
479         public static void quit() {
480                 if (sequencer.isOpen()) sequencer.close();
481                 if (synthesizer.isOpen()) synthesizer.close();
482                 System.exit(0);
483         }
484         
485         public static void setTrackSolo(Track track, boolean on){
486                 trackSolo.put(track, new Boolean(on));  
487         }
488
489         public static void setTrackMute(Track track, boolean on){
490                 trackMute.put(track, new Boolean(on));  
491         }
492 }