]> ruin.nu Git - moosique.git/blob - Moosique.java
removed some stuff
[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 MetaMessage tempoMsg, timeSigMsg;
23
24         private static String filename, fileArg;
25         private static long editPosition;
26         private static boolean makeGUI = true, isEdited;
27         private static Thread player;
28         public static final int RESOLUTION = 96, DEFAULT_TRACKS = 4;
29
30         /** 
31          * Starts the application.
32          */
33         public static void main (String[] args) {
34                 System.out.println("\nMoosique version 1.0\n");
35
36                 // Parses command-line arguments.
37                 for (int i = 0; i < args.length; i++) {
38                         if (args[i].equals("-n")) {makeGUI = false;}
39                         else if (fileArg == null) {fileArg = args[i];}
40                 }
41
42                 // Acquires MIDI devices and connects them.
43                 System.out.print("Initializing MIDI devices.");
44                 try {
45                         sequencer = MidiSystem.getSequencer();
46                         System.out.print(".");
47                         sequencer.open();
48                         synthesizer = MidiSystem.getSynthesizer();
49                         System.out.print(".");
50                         synthesizer.open();
51                         sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
52                         channels = synthesizer.getChannels();
53                         setActiveChannel(0);
54                 } catch (MidiUnavailableException e) {
55                         System.out.println("Failed, quitting.");
56 //                      System.exit(1);
57                 }
58                 System.out.println("Done");
59
60                 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
61                 if (fileArg != null) {
62                         System.out.print("Loading MIDI sequence from " + fileArg + "...");
63                         if (!load(fileArg)) {
64                                 System.out.println("Failed");
65                                 clearSequence();
66                         } else {
67                                 System.out.println("Done");
68                         }
69                 } else {
70                         // Otherwise creates a new empty one.
71                         clearSequence();
72                 }
73
74                 // Builds GUI, unless n-flag is set.
75                 if (makeGUI) {
76                         System.out.print("Building GUI...");
77                         try {
78                                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
79                         } catch (Exception e) {}
80                         gui = new MooGUI(seq);
81                         System.out.println("Done");
82                 } else {
83                         System.out.print("Playing...");
84                         play();
85                         while (sequencer.isRunning()) {}
86                         System.out.println("Done");
87                         quit();
88                 }
89         }
90
91         /** 
92          * Returns the GUI.
93          * @return the GUI
94          */
95         public static MooGUI getGUI() {
96                 return gui;
97         }
98
99         /** 
100          * Returns the current sequence.
101          * @return the current sequence
102          */
103         public static Sequence getSequence() {
104                 return seq;
105         }
106
107         /** 
108          * Returns the current sequencer.
109          * @return the current sequencer
110          */
111         public static Sequencer getSequencer() {
112                 return sequencer;
113         }
114
115         /** 
116          * Returns the MidiChannels of the selected synthesizer.
117          * @return the available MidiChannels
118          */
119         public static MidiChannel[] getChannels() {
120                 return channels;
121         }
122
123         /** 
124          * Returns the MidiChannels of the selected synthesizer.
125          * @return the available MidiChannels
126          */
127         public static MidiChannel getChannel(int i) {
128                 return channels[i];
129         }
130
131         /** 
132          * Returns the currently active MidiChannel.
133          * @return the active MidiChannel
134          */
135         public static MidiChannel getActiveChannel() {
136                 return activeChannel;
137         }
138
139         /** 
140          * Sets the currently active MidiChannel.
141          * @param channel       the number of the MidiChannel to activate
142          */
143         public static void setActiveChannel(int channel) {
144                 activeChannel = channels[channel];
145         }
146
147         /** 
148          * Replaces the current sequence with a new one, holding three empty tracks.
149          */
150         public static void clearSequence() {
151                 // Creates a new sequence and sends it to the sequencer.
152                 try {
153                         seq = new Sequence(Sequence.PPQ, RESOLUTION, DEFAULT_TRACKS);
154                         sequencer.setSequence(seq);
155                 } catch (InvalidMidiDataException e) {}
156                 // Sends sequence to GUI.
157                 if (gui != null) gui.setSequence(seq);
158         }
159
160         /** 
161          * Starts playback of the current sequence.
162          */
163         public static void play() {
164                 sequencer.setTickPosition(editPosition);
165                 resume();
166         }
167
168         /** 
169          * Pauses playback of the current sequence.
170          */
171         public static void pause() {
172                 if (sequencer.isRunning()) {
173                         sequencer.stop();
174                 }
175                 if (player != null) player.interrupt();
176         }
177
178         /** 
179          * Resumes playback of the current sequence.
180          */
181         public static void resume() {
182                 gui.update(0);
183                 sequencer.start();
184
185                 // Disables input to volatile components
186                 // gui.disable();
187
188                 // Creates the visualization thread and starts it.
189                 player = new Thread () {
190                         public void run() {
191                                 while(sequencer.isRunning()) gui.update(sequencer.getTickPosition());
192                                 Moosique.stop();
193                         }
194                 };
195                 player.start();
196         }
197
198         /** 
199          * Stops playback of the current sequence.
200          */
201         public static void stop() {
202                 if (sequencer.isRunning()) {
203                         sequencer.stop();
204                 }
205                 sequencer.setTickPosition(editPosition);
206                 if (player != null) player.interrupt();
207                 gui.update((long)0);
208         }
209
210         /** 
211          * Returns the current editing position of the sequencer.
212          * @return the tick position
213          */
214         public static long getPosition() {
215                 return editPosition;
216         }
217
218         /** 
219          * Sets the current editing position of the sequencer.
220          * @param ticks         the tick position
221          */
222         public static void setPosition(long ticks) {
223                 editPosition = ticks;
224         }
225
226         /** 
227          * Returns the tempo of the current sequence.
228          * @return the tick position
229          */
230         public static int getTempo() {
231                 if (tempoMsg == null) return 0;
232                 return 120;
233         }
234
235         /** 
236          * Sets the current editing position of the sequencer.
237          * @param ticks         the tick position
238          */
239         public static void setTempo(int bpm) {
240                 // tempoMsg, timeSigMsg
241         }
242
243         /** 
244          * Returns the tempo of the current sequence.
245          * @return the tick position
246          */
247         public static int getTimeSig() {
248                 if (timeSigMsg == null) return 0;
249                 return 120;
250         }
251
252         /** 
253          * Sets the current editing position of the sequencer.
254          * @param ticks         the tick position
255          */
256         public static void setTimeSig(int bpm) {
257                 // tempoMsg, timeSigMsg
258         }
259
260         /** 
261          * Returns true if the current sequence has been edited.
262          * @return the tick position
263          */
264         public static boolean isEdited() {
265                 return isEdited;
266         }
267
268         /** 
269          * Sets the current sequence as edited, which implies prompts when loading a new sequence.
270          */
271         public static void setEdited() {
272                 isEdited = true;
273         }
274
275         /** 
276          * Rewinds the current sequence the given number of measures.
277          * @param measures      the number of measures to rewind
278          */
279         public static void rewind(long ticks) {
280                 editPosition -= ticks;
281         }
282
283         /** 
284          * Fast forwards the current sequence the given number of measures.
285          * @param measures      the number of measures to fast forward
286          */
287         public static void forward(long ticks) {
288                 editPosition += ticks;
289         }
290
291         /** 
292          * Loads the MooSequence in the given file.
293          * @param filename      the filename to use
294          */
295         public static boolean load(String file) {
296                 // Loads sequence from file
297                 filename = file;
298                 try {
299                         seq = MidiSystem.getSequence(new File(filename));
300                 } catch (InvalidMidiDataException e) {
301                         return false;
302                 } catch (IOException e) {
303                         return false;
304                 }
305                 isEdited = false;
306
307                 Track[] tracks = seq.getTracks();
308
309                 // Stores tempo and time signature.
310                 MidiMessage msg;
311                 MetaMessage metaMsg;
312                 for (int i = 0; i < tracks[0].size(); i++) {
313                         msg = tracks[0].get(i).getMessage();
314                         if (msg.getStatus() == MetaMessage.META) {
315                                 metaMsg = (MetaMessage)msg;
316                                 if (metaMsg.getType() == 81) {
317                                         tempoMsg = metaMsg;
318                                 } else if (metaMsg.getType() == 88) {
319                                         timeSigMsg = (MetaMessage)msg;
320                                 }
321
322                         }
323                 }
324
325                 // Searches the sequence for NoteOn events
326                 MidiEvent noteOn, noteOff = null, nextEvent;
327                 MidiMessage nextMsg;
328                 ShortMessage shortMsg;
329                 ArrayList noteOns, noteOffs;
330                 for (int i = 0; i < tracks.length; i++) {
331                          noteOns = new ArrayList(tracks.length);
332         /*
333                         Collections.sort(track[i].events, new Comparator() {
334                                 public int compare(Object o1, Object o2) {
335                                         return ((MidiEvent)o2).getTick() - ((MidiEvent)o1).getTick();
336                                 }
337                         });
338         */
339                         for (int j = 0; j < tracks[i].size(); j++) {
340                                 noteOn = tracks[i].get(j);
341                                 if (noteOn.getMessage().getStatus() == ShortMessage.NOTE_ON) {
342                                         // Finds the corresponding NoteOff event
343                                         for (int k = j + 1; k < tracks[i].size(); k++) {
344                                                 nextEvent = tracks[i].get(k);
345                                                 nextMsg = nextEvent.getMessage();
346                                                 if (nextMsg instanceof ShortMessage) {
347                                                         shortMsg = (ShortMessage) nextMsg;
348                                                         if (shortMsg.getCommand() == ShortMessage.NOTE_OFF && shortMsg.getChannel() == ((ShortMessage)noteOn.getMessage()).getChannel() && shortMsg.getData1() == ((ShortMessage)noteOn.getMessage()).getData1()) {
349                                                                 noteOff = nextEvent;
350                                                                 break;
351                                                         }
352                                                 }
353                                         }
354                                         // Replaces the NoteOn event with a MooNote, if possible with the corresponding NoteOff event
355                                         tracks[i].remove(noteOn);
356                                         if (noteOff != null) {
357                                                 tracks[i].add(new MooNote(noteOn, noteOff));
358                                         } else {
359                                                 tracks[i].add(new MooNote(noteOn));
360                                         }
361                                 }
362                         }
363                 }
364                 // Sends sequence to GUI and sequencer, then returns
365                 if (gui != null) gui.setSequence(seq);
366                 try {
367                         sequencer.setSequence(seq);
368                 } catch (InvalidMidiDataException e) {}
369                 return true;
370         }
371
372         /** 
373          * Saves the current sequence to the given filename
374          * @param file  the filename to use
375          */
376         public static void saveAs(String file) {
377                 try {
378                         MidiSystem.write(seq, 1, new File(filename));
379                 } catch (IOException e) {}
380                 filename = file;
381                 gui.setStatus("Saved " + file);
382         }
383
384         /** 
385          * Saves the current sequence to the previously given filename.
386          */
387         public static void save() {
388                 saveAs(filename);
389         }
390
391         /** 
392          * Releases all reserved devices and exits the program.
393          */
394         public static void quit() {
395                 if (sequencer.isOpen()) sequencer.close();
396                 if (synthesizer.isOpen()) synthesizer.close();
397                 System.exit(0);
398         }
399 }