/** Closes MIDI resources - be sure to call this after play() has returned. */ public void close() { getSequencer().close(); try { if (MidiSystem.getSynthesizer() != null) { MidiSystem.getSynthesizer().close(); } } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.GENERAL_ERROR + e.getMessage()); } }
public void PlayMidiFile(String name, String filename) { Sequencer seq = null; Transmitter seqTrans = null; Synthesizer synth; Receiver synthRcvr = null; File midiFile = null; try { seq = MidiSystem.getSequencer(); seqTrans = seq.getTransmitter(); synth = MidiSystem.getSynthesizer(); synthRcvr = synth.getReceiver(); midiFile = new File(filename); if (seq == null) { Debug.showMessage("MidiCSD::PlayMidiFile: Sequencer nicht gefunden!"); } else { seq.open(); seqTrans.setReceiver(synthRcvr); Sequence mySeq; mySeq = MidiSystem.getSequence(midiFile); new Player(name, seq, mySeq, synth, m_playing).start(); } } catch (MidiUnavailableException e) { Debug.showException(e, "MidiCSD::PlayMidiFile: MidiUnavailable" + e.getMessage()); } catch (InvalidMidiDataException e) { Debug.showException(e, "MidiCSD::PlayMidiFile: InvalidMidiDataException" + e.getMessage()); } catch (IOException e) { Debug.showException(e, "MidiCSD::PlayMidiFile:IOException (fn:" + filename + ")"); } }
private void loadSoundBank(File soundbankFile) { try { synthesizer.close(); Soundbank sb = MidiSystem.getSoundbank(soundbankFile); synthesizer = MidiSystem.getSynthesizer(); synthesizer.open(); System.out.println("soundbank added: " + sb); if (sb != null) { System.out.println("soundbank supported: " + synthesizer.isSoundbankSupported(sb)); boolean bInstrumentsLoaded = synthesizer.loadAllInstruments(sb); System.out.println("Instruments loaded: " + bInstrumentsLoaded); } } catch (MidiUnavailableException e) { e.printStackTrace(); } catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void allNotesOff() { try { allNotesOff(MidiSystem.getSynthesizer()); } catch (MidiUnavailableException e) { throw new JFugueException(JFugueException.GENERAL_ERROR); } }
public boolean initialize() { boolean success = true; try { sequencer = MidiSystem.getSequencer(); sequencer.addMetaEventListener(this); if (synthesizer == null) { if ((synthesizer = MidiSystem.getSynthesizer()) == null) { Application.debug("getSynthesizer() failed!"); return false; } Soundbank sb = synthesizer.getDefaultSoundbank(); if (sb != null) { instruments = synthesizer.getDefaultSoundbank().getInstruments(); synthesizer.loadInstrument(instruments[0]); } channels = synthesizer.getChannels(); } } catch (MidiUnavailableException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } return success; }
public boolean init(int nbells) { fNBells = nbells; try { fSequencer = MidiSystem.getSequencer(); fSequencer.addMetaEventListener(fListener); fSynthesizer = MidiSystem.getSynthesizer(); fMidiOut = fSynthesizer.getReceiver(); fSequencer.getTransmitter().setReceiver(fMidiOut); /* System.out.println(" Listing available midi devices: "); MidiDevice.Info[] info = MidiSystem.getMidiDeviceInfo(); for (int i=0; i<info.length; i++) { Class c = MidiSystem.getMidiDevice(info[i]).getClass(); System.out.println(" MIDI device "+i+": "+info[i]+" is a "+c); } System.out.println("Using Sequencer "+fSequencer.getClass()+" and receiver "+fMidiOut.getClass()); */ } catch (MidiUnavailableException e) { System.out.println("Could not obtain MIDI device: " + e); return false; } return true; }
public Sequencer(int instrument, int tempo) { // Set up initial settings for the sequencer this.instrument = instrument; this.tempo = tempo; Synthesizer synth; ticks = 0; velocity = 64; // Mid volume try { // Setup values to create sequencer sequence = new Sequence(Sequence.PPQ, 16); sequencer = MidiSystem.getSequencer(); sequencer.open(); synth = MidiSystem.getSynthesizer(); synth.open(); sequencer.getTransmitter().setReceiver(synth.getReceiver()); sequencer.setTempoInBPM(tempo); track = sequence.createTrack(); } catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (MidiUnavailableException e) { e.printStackTrace(); } }
static { try { Synthesizer synth = MidiSystem.getSynthesizer(); synth.open(); channels = synth.getChannels(); } catch (MidiUnavailableException ex) { System.out.println(ex.getMessage()); } }
public MidiViewImpl() { try { this.synth = MidiSystem.getSynthesizer(); this.receiver = synth.getReceiver(); this.synth.open(); } catch (MidiUnavailableException e) { e.printStackTrace(); } }
public synchronized void init() throws MidiUnavailableException { if (unusedChannels != null) return; if (synthesizer == null) synthesizer = MidiSystem.getSynthesizer(); if (!synthesizer.isOpen()) synthesizer.open(); MidiChannel[] chn = synthesizer.getChannels(); playTasks = new ArrayList<PlayTask>(); if (receiver == null) receiver = synthesizer.getReceiver(); unusedChannels = new ArrayList<Integer>(chn.length); for (int i = 0; i < chn.length; i++) if (i != 9) unusedChannels.add(i); }
public MidiHandler(int mTempo) { try { syn = MidiSystem.getSynthesizer(); syn.open(); mc = syn.getChannels(); tempo = mTempo; } catch (MidiUnavailableException ex) { Logger.getLogger(MidiHandler.class.getName()).log(Level.SEVERE, null, ex); } }
/* * Get synthesizer. */ public Synthesizer getSynthesizer() { Synthesizer synthesizer = null; try { synthesizer = MidiSystem.getSynthesizer(); synthesizer.open(); } catch (Exception ex) { System.out.println(ex); System.exit(1); } return synthesizer; }
public MidiToWavRenderer() throws MidiUnavailableException, InvalidMidiDataException, IOException { try { synth = (AudioSynthesizer) MidiSystem.getSynthesizer(); } catch (ClassCastException e) { throw new Error( "Please make sure Gervill is included in the classpath: " + "it should be de default synth. These are the currently installed synths: " + MidiSystem.getMidiDeviceInfo().toString(), e); } }
void init_midi(LContext lcontext) { if (!midiSynthInitialized) { midiSynthInitialized = true; try { midiSynth = MidiSystem.getSynthesizer(); midiSynth.open(); if (midiSynth.getDefaultSoundbank() == null) { ((LContext) lcontext).canvas.setMessage ("Reading sound bank from server. Please wait..."); if (lcontext != null) { /* empty */ } URL url = new URL(((LContext) lcontext).codeBase + "soundbank.gm"); Soundbank soundbank = MidiSystem.getSoundbank(url); if (soundbank != null) { midiSynth.loadAllInstruments(soundbank); ((LContext) lcontext).canvas.setMessage(""); } else { midiSynth.close(); midiSynth = null; } } } catch (MidiUnavailableException midiunavailableexception) { midiunavailableexception.printStackTrace(); midiSynth = null; } catch (MalformedURLException malformedurlexception) { malformedurlexception.printStackTrace(); midiSynth = null; } catch (InvalidMidiDataException invalidmididataexception) { invalidmididataexception.printStackTrace(); midiSynth = null; } catch (IOException ioexception) { ioexception.printStackTrace(); midiSynth = null; } catch (AccessControlException accesscontrolexception) { accesscontrolexception.printStackTrace(); midiSynth = null; } if (midiSynth != null) { MidiChannel[] midichannels = midiSynth.getChannels(); for (int i = 0; i < midichannels.length; i++) { if (midichannels[i] != null) midichannels[i].programChange(0); } } else ((LContext) lcontext).canvas.setMessage ("No soundbank; note & drum commands disabled."); } }
/** * Constructs a default MidiView by constructing a synthesizer and receiver, and turning the * synthesizer open. If a MidiSystem is unavailable, an exception is thrown. */ public MidiView(MusicEditorModel model) { Synthesizer synthesizer = null; Receiver rcvr = null; try { synthesizer = MidiSystem.getSynthesizer(); rcvr = synthesizer.getReceiver(); } catch (MidiUnavailableException e) { e.printStackTrace(); } this.synth = synthesizer; try { this.synth.open(); } catch (MidiUnavailableException e) { System.err.println("Midi device is unavailable"); } this.receiver = rcvr; this.model = new MusicEditorViewModel(model); }
/** Gets the default transmitter and receiver, and then links them. */ private void linkTransmitterToReceiver() { try { // Set up the sequencer (including its tempo) sequencer.open(); sequencer.setSequence(sequence); sequencer.setTempoInBPM(song.getBPM()); // Get the system's default synthesizer and set that up, too. Synthesizer synth = MidiSystem.getSynthesizer(); synth.open(); // Get the receiver and transmitter to use and set those up. Receiver receiver = synth.getReceiver(); Transmitter transmitter = sequencer.getTransmitter(); transmitter.setReceiver(receiver); } catch (Exception ex) { // Something went wrong. ex.printStackTrace(); System.exit(1); } }
public boolean open() { try { if (synthesizer == null) { if ((synthesizer = MidiSystem.getSynthesizer()) == null) { System.out.println("getSynthesizer() failed!"); return false; } } synthesizer.open(); sequencer = MidiSystem.getSequencer(); sequencer.addMetaEventListener(new ProcessMeta()); sequence = new Sequence(Sequence.PPQ, 10); } catch (Exception ex) { System.out.println("midi exception 1 "); ex.printStackTrace(); return false; } System.out.println("midi opening"); Soundbank sb = synthesizer.getDefaultSoundbank(); if (sb != null) { instruments = synthesizer.getDefaultSoundbank().getInstruments(); synthesizer.loadInstrument(instruments[0]); } MidiChannel midiChannels[] = synthesizer.getChannels(); numChannels = midiChannels.length; channels = new ChannelData[midiChannels.length]; if (channels.length == 0) return false; for (int i = 0; i < channels.length; i++) { channels[i] = new ChannelData(midiChannels[i], i); } cc = channels[0]; return true; }
public static void main(String[] args) throws Exception { synth = MidiSystem.getSynthesizer(); synth.open(); synth.loadAllInstruments(synth.getDefaultSoundbank()); // int s = 0; // for(Instrument i : synth.getAvailableInstruments()){ // System.out.println(s+" "+i.getName()); // s++; // } chan = synth.getChannels()[0]; for (Instrument i : synth.getLoadedInstruments()) if (i.getName().toLowerCase().trim().contains("sine")) chan.programChange(i.getPatch().getProgram()); if (chan.getProgram() == 0) JOptionPane.showMessageDialog(null, "Could not find a valid instrument. Sound is disabled"); // chan.programChange(synth.getLoadedInstruments()[197].getPatch().getProgram()); for (int i = 0; i < array.length; i++) marked.add(-5); rianr(array); window.setSize(new Dimension(640, 480)); window.setLocation(0, 0); window.setVisible(true); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setTitle("Array Visualizer"); uf = new UtilFrame(window); // AUDIO THREAD new Thread() { @Override public void run() { while (true) { chan.allNotesOff(); if (SOUND == false) { continue; } int tmp = 1; for (int i : marked) if (i != -5) tmp++; for (int i : marked) if (i != -5) { int pitch = (int) Math.round( (double) array[Math.min(Math.max(i, 0), array.length - 1)] / array.length * 96 + 16); // int vel = (int)(((128-pitch)/320.0+0.4) * (128.0/Math.pow(tmp,0.33))); int vel = (int) (64.0 / Math.pow(tmp, 0.5)); chan.noteOn(pitch, vel); } // ((int)((127-(array[Math.min(Math.max(i, // 0),array.length-1)]/16.0))/Math.sqrt(calcVel())))*5 // double tmp = (array[Math.min(Math.max(i, 0),array.length-1)]/32.0+47); // chan.setPitchBend(8192*2-(int)((tmp-Math.floor(tmp))*8192*2)); /* ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int i : marked) if(i != -5) tmp.add(i); if(tmp.size() > 0){ do{ int i = tmp.get(snd%tmp.size()); snd++; chan.noteOn(array[Math.min(Math.max(i, 0),array.length-1)]/32+47, 127); double tmpd = (array[Math.min(Math.max(i, 0),array.length-1)]/32.0+47); chan.setPitchBend(8192*2-(int)((tmpd-Math.floor(tmpd))*8192*2)); }while(false);}*/ try { sleep(1); } catch (Exception e) { } } } }.start(); // DRAW THREAD new Thread() { @Override public void run() { int cw = window.getWidth(); int ch = window.getHeight(); Image img = window.createVolatileImage(cw, ch); // Graphics g = window.getGraphics(); Graphics g = img.getGraphics(); double xscl, yscl; while (true) { if (window.getWidth() != cw || window.getHeight() != ch || window.getX() != cx || window.getY() != cy) { uf.reposition(); if (v != null && v.isVisible()) v.reposition(); cx = window.getX(); cy = window.getY(); } if (window.getWidth() != cw || window.getHeight() != ch) { cw = window.getWidth(); ch = window.getHeight(); img = window.createVolatileImage(cw, ch); fon = new Font("TimesRoman", Font.PLAIN, (int) (cw / 1280.0 * 25)); g = img.getGraphics(); } int gamt = 32; // (int)(frames/1000.0%64); g.setColor(new Color(gamt, gamt, gamt)); g.fillRect(0, 0, img.getWidth(null), img.getHeight(null)); xscl = (double) window.getWidth() / array.length; yscl = (double) (window.getHeight() - 30) / array.length; int amt = 0; int circamt = array.length / 2; frames++; if (CIRCLEDRAW) for (int i = 0; i < array.length; i++) { if (marked.contains(i) || marked.contains(i - 1) || marked.contains(i - 2) || marked.contains(i - 3)) g.setColor(Color.BLACK); else g.setColor(getIntColor(array[i])); // COLOR ONLY NO LENGTH if (COLORONLY) g.drawLine( window.getWidth() / 2, window.getHeight() / 2, window.getWidth() / 2 + (int) (Math.sin(i * Math.PI / circamt) * (window.getWidth() - 64) / 2.0), window.getHeight() / 2 - (int) (Math.cos(i * Math.PI / circamt) * (window.getHeight() - 96) / 2.0)); else if (PIXELDRAW) g.fillRect( window.getWidth() / 2 + (int) (Math.sin(i * Math.PI / circamt) * ((window.getWidth() - 64) / 2.0 * (array[i] / (double) array.length))), window.getHeight() / 2 - (int) (Math.cos(i * Math.PI / circamt) * ((window.getHeight() - 96) / 2.0 * (array[i] / (double) array.length))), (int) (2 * (window.getWidth() / 640.0)), (int) (2 * (window.getHeight() / 480.0))); // LENGTH AND COLOR else g.drawLine( window.getWidth() / 2, window.getHeight() / 2, window.getWidth() / 2 + (int) (Math.sin(i * Math.PI / circamt) * ((window.getWidth() - 64) / 2.0 * (array[i] / (double) array.length))), window.getHeight() / 2 - (int) (Math.cos(i * Math.PI / circamt) * ((window.getHeight() - 96) / 2.0 * (array[i] / (double) array.length)))); } else for (int i = 0; i < array.length; i++) { if (marked.contains(i) || marked.contains(i - 1) || marked.contains(i - 2) || marked.contains(i - 3)) g.setColor(Color.BLACK); else g.setColor(getIntColor(array[i])); int y = 0; int width = (int) (xscl * i) - amt; if (width > 0) { if (COLORONLY) { y = (int) (window.getHeight() - 750 * yscl); g.fillRect(amt, y, width, Math.max((int) (750 * yscl), 1)); g.setColor(getRevColor()); g.fillRect((int) (i * xscl), y, width, 6); } else if (PIXELDRAW) { y = (int) (window.getHeight() - array[i] * yscl); g.fillRect(amt, y, width, 3); } else { y = (int) (window.getHeight() - array[i] * yscl); g.fillRect(amt, y, width, Math.max((int) (array[i] * yscl), 1)); g.setColor(getRevColor()); g.fillRect(amt, y, width, 6); } } amt += width; } int coltmp = 255; // (int)Math.abs(Math.sin(frames*0.01)*255); g.setColor(new Color(coltmp, coltmp, coltmp)); Font f = g.getFont(); g.setFont(fon); g.drawString(heading, 10, (int) (cw / 1280.0 * 20) + 30); g.drawString( "Comparisons: " + comps + " Array Accesses: " + aa, 10, (int) (cw / 1280.0 * 40) + 30); g.setFont(f); Graphics g2 = window.getGraphics(); g2.setColor(Color.BLACK); g2.drawImage(img, 0, 0, null); } } public Color getIntColor(int i) { return Color.getHSBColor(((float) i / array.length), 1.0F, 0.8F); } public Color getRevColor() { return getIntColor((int) (Math.sin(frames / 66.67) * array.length)); } }.start(); uf.setVisible(false); v = new ViewPrompt(window); while (v.isVisible()) Thread.sleep(1); uf.setVisible(true); // bogoSort(); // while(true){ // clearmarked(); // // //heading = "Linear Search"; // // //Arrays.sort(array); // //marked.set(1,730); // //linearSearch(730); // //refresharray(); // // //heading = "Binary Search"; // // //Arrays.sort(array); // //marked.set(1, 730); // //binarySearch(730); // // //heading = "Shatter-Time Sort"; // // //timeSort(); // // //chan.allNotesOff(); // //refresharray(); // weaveMergeSort(0, array.length-1); // refresharray(); // cocktailShakerSort(); // refresharray(); // radixLSDsort(4); // refresharray() // ;RadixLSDInPlace.inPlaceRadixLSDSort(10);refresharray(); // // heading = "Insertion Sort"; // // insertionSort(); // // chan.allNotesOff(); // refresharray(); // heading = "Bubble Sort"; // // bubbleSort(); // // chan.allNotesOff(); // refresharray(); // heading = "Selection Sort"; // // selectionSort(); // // chan.allNotesOff(); // refresharray(); // heading = "Cocktail Shaker Sort"; // // cocktailShakerSort(); // // chan.allNotesOff(); // refresharray(); // heading = "Double Selection Sort"; // // doubleSelectionSort(array); // // chan.allNotesOff(); // refresharray(); // heading = "Merge Sort In-Place"; // // mergeSort(0, array.length - 1); // // chan.allNotesOff(); // refresharray(); // heading = "Merge Sort Out-of-Place"; // // mergeSortOP(); // // chan.allNotesOff(); // refresharray(); // // heading = "Gravity Sort (Abacus/Bead)"; // // gravitySort(); // // chan.allNotesOff(); // refresharray(); // // heading = "Quick Sort"; // // quickSort(array, 0, array.length-1); // // chan.allNotesOff(); // refresharray(); // heading = "Counting Sort"; // // countingSort(); // // chan.allNotesOff(); // refresharray(); // heading = "Radix LSD Sort"; // // radixLSDsort(4); // // chan.allNotesOff(); // refresharray(); // heading = "Radix LSD In-Place Sort"; // // inPlaceRadixLSDSort(10); // // chan.allNotesOff(); // refresharray(); // heading = "Radix MSD Sort"; // // radixMSDSort(4); // refresharray(); // //heading = "Shatter Partition"; // // //shatterPartition(1); // // //chan.allNotesOff(); // //refresharray(); // heading = "Shatter Sort"; // // shatterSort(128); // // chan.allNotesOff(); // refresharray(); // //heading = "Simple Shatter Sort"; // // //simpleShatterSort(128, 4); // // //chan.allNotesOff(); // //refresharray(); // // keep on keeping on while (window.isActive()) Thread.sleep(1); }
/** * Converts the given tune to a midi sequence. * * @param tune The tune to be converted. * @return The midi sequence of the tune. */ public Sequence toMidiSequence(Tune tune) { Sequence sequence = null; try { if (instrument == null) { Synthesizer synth = MidiSystem.getSynthesizer(); synth.open(); try { setInstrument(synth.getAvailableInstruments()[0]); } finally { synth.close(); } } // Sequence in ticks per quarter note : PPQ = Pulse Per Quarter Note // Resolution is expressed in ticks per beat. // Last parameter "1" is the number of tracks. sequence = new Sequence(Sequence.PPQ, SEQUENCE_RESOLUTION, 1); // Set the instrument on channel 0 ShortMessage sm = new ShortMessage(); sm.setMessage(ShortMessage.PROGRAM_CHANGE, 0, instrument.getPatch().getProgram(), 0); Track track = sequence.createTrack(); track.add(new MidiEvent(sm, 0)); // long trackLengthInTicks = track.ticks(); int lastRepeatOpen = -1; int repeatNumber = 1; boolean inWrongEnding = false; KeySignature tuneKey = null; KeySignature currentKey = null; Hashtable partsKey = new Hashtable(); long elapsedTime = 0; NoteAbstract[] graceNotes = null; Music staff = tune.getMusicForAudioRendition(); Iterator it = staff.getVoices().iterator(); while (it.hasNext()) { Voice voice = (Voice) it.next(); int i = 0; // StaffItem iterator while (i < voice.size()) { if (!inWrongEnding) { // ==================================================================== TEMPO if (voice.elementAt(i) instanceof abc.notation.Tempo) { addTempoEventsFor( track, elapsedTime, getMidiMessagesFor((Tempo) voice.elementAt(i))); // , trackLengthInTicks)); } else /*if (voice.elementAt(i) instanceof abc.notation.PartLabel) { //Imagine... part A in Gmaj, B in Amin //in tune you have K:G, P:A, ... P:B, K:Am //if you have part order ABA, when you return to A //you stay in Amin. This stores the tuneKey when a //new part appear, and restitute it when part is played again abc.notation.PartLabel pl = (abc.notation.PartLabel) voice.elementAt(i); if (partsKey.get(pl.getLabel()+"") == null) { partsKey.put(pl.getLabel()+"", tuneKey); } else { tuneKey = (KeySignature) partsKey.get(pl.getLabel()+""); } } else*/ // ==================================================================== KEY SIGNATURE if (voice.elementAt(i) instanceof abc.notation.KeySignature) { tuneKey = (KeySignature) (voice.elementAt(i)); currentKey = new KeySignature(tuneKey.getAccidentals()); } else // ==================================================================== NOTE // Notes ending ties should be ignored. Already taken into // account in getNoteLengthInTicks(Note) if (voice.elementAt(i) instanceof abc.notation.Note && !((abc.notation.Note) voice.elementAt(i)).isEndingTie()) { Note note = (Note) voice.elementAt(i); long noteDuration; boolean fermata = false; Vector decorationNotes = new Vector(); if (note.hasGeneralGracing() || note.hasDecorations()) { Decoration[] d = note.getDecorations(); for (int j = 0; j < d.length; j++) { switch (d[j].getType()) { case Decoration.FERMATA: case Decoration.FERMATA_INVERTED: fermata = true; break; case Decoration.LOWERMORDENT: case Decoration.UPPERMORDENT: case Decoration.DOUBLE_LOWER_MORDANT: case Decoration.DOUBLE_UPPER_MORDANT: case Decoration.TRILL: case Decoration.TURN: // GRUPETTO_UP case Decoration.TURN_INVERTED: // GRUPETTO_DOWN case Decoration.TURNX: case Decoration.TURNX_INVERTED: Note n = new Note(note.getHeight()); n.setAccidental(note.getAccidental(currentKey)); Note o = new Interval(Interval.SECOND, Interval.MAJOR, Interval.UPWARD) .calculateSecondNote(n); Note m = new Interval(Interval.SECOND, Interval.MAJOR, Interval.DOWNWARD) .calculateSecondNote(n); // TODO ornament templates: regular, musette, balkan... // n.setStrictDuration(Note.SIXTEENTH); // o.setDuration((short)(Note.EIGHTH+Note.SIXTEENTH)); o.setAccidental(Accidental.NONE); m.setAccidental(Accidental.NONE); n.setStrictDuration(Note.THIRTY_SECOND); m.setStrictDuration(Note.THIRTY_SECOND); o.setStrictDuration(Note.THIRTY_SECOND); switch (d[j].getType()) { case Decoration.DOUBLE_LOWER_MORDANT: decorationNotes.add(n); decorationNotes.add(m); case Decoration.LOWERMORDENT: decorationNotes.add(n); decorationNotes.add(m); break; case Decoration.DOUBLE_UPPER_MORDANT: case Decoration.TRILL: decorationNotes.add(n); decorationNotes.add(o); case Decoration.UPPERMORDENT: decorationNotes.add(n); decorationNotes.add(o); break; case Decoration.TURNX_INVERTED: case Decoration.TURN: decorationNotes.add(o); decorationNotes.add(n); decorationNotes.add(m); break; case Decoration.TURNX: case Decoration.TURN_INVERTED: decorationNotes.add(m); decorationNotes.add(n); decorationNotes.add(o); } break; } } // currently not used // future use: playing rolls, slides, etc. } long graceNotesDuration = 0; if (note.hasGracingNotes() || (decorationNotes.size() > 0)) { graceNotes = note.getGracingNotes(); // gracing are eighth note for graphical rendition // and because that's it in the parser // adapt duration to note length int divisor = 1; if (note.getStrictDuration() >= Note.HALF) divisor = 1; // grace is an eighth else if (note.getStrictDuration() >= Note.QUARTER) divisor = 2; // 16th else if (note.getStrictDuration() >= Note.EIGHTH) divisor = 4; // 32nd else divisor = 8; // 64th if (note.hasGracingNotes()) { for (int j = 0; j < graceNotes.length; j++) { noteDuration = getNoteLengthInTicks(graceNotes[j], staff) / divisor; graceNotesDuration += noteDuration; if (graceNotes[j] instanceof Note) playNote( (Note) graceNotes[j], i, currentKey, elapsedTime, noteDuration, track); else playMultiNote( (MultiNote) graceNotes[j], i, currentKey, /*elapsedTime,*/ noteDuration, track, staff); elapsedTime += noteDuration; } } for (int j = 0; j < decorationNotes.size(); j++) { noteDuration = getNoteLengthInTicks((Note) decorationNotes.elementAt(j), staff); graceNotesDuration += noteDuration; playNote( (Note) decorationNotes.elementAt(j), i, currentKey, elapsedTime, noteDuration, track); elapsedTime += noteDuration; } } // The note duration if the note isn't part of a tuplet. noteDuration = getNoteLengthInTicks(note, staff) - graceNotesDuration; if (noteDuration <= 0) // in case of too much grace notes noteDuration = getNoteLengthInTicks(note, staff); if (fermata) noteDuration *= 2; playNote(note, i, currentKey, elapsedTime, noteDuration, track); elapsedTime += noteDuration; } else // ==================================================================== MULTI NOTE if ((voice.elementAt(i) instanceof abc.notation.MultiNote)) { MultiNote multiNote = (MultiNote) voice.elementAt(i); playMultiNote(multiNote, i, currentKey, elapsedTime, track, staff); elapsedTime += getNoteLengthInTicks(multiNote, staff); } } // endif (!inWrongEnding) // ====================================================================== REPEAT BAR LINE if (voice.elementAt(i) instanceof abc.notation.RepeatBarLine) { RepeatBarLine bar = (RepeatBarLine) voice.elementAt(i); if (repeatNumber < bar.getRepeatNumbers()[0] && lastRepeatOpen != -1) { repeatNumber++; i = lastRepeatOpen; } else if (repeatNumber > bar.getRepeatNumbers()[0]) inWrongEnding = true; else inWrongEnding = false; } else // ====================================================================== BAR LINE OPEN / // CLOSE if (voice.elementAt(i) instanceof abc.notation.BarLine) { // currentKey = new KeySignature(tuneKey.getAccidentals()); switch (((BarLine) (voice.elementAt(i))).getType()) { case BarLine.SIMPLE: break; case BarLine.REPEAT_OPEN: lastRepeatOpen = i; repeatNumber = 1; break; case BarLine.REPEAT_CLOSE: if (repeatNumber < 2 && lastRepeatOpen != -1) { repeatNumber++; i = lastRepeatOpen; } else { repeatNumber = 1; lastRepeatOpen = -1; } break; // TODO case BarLine.BEGIN_AND_END_REPEAT } } // Whatever kind of bar line it is if (voice.elementAt(i) instanceof abc.notation.BarLine) { currentKey = new KeySignature(tuneKey.getAccidentals()); } i++; } // end while each element in voice } // end while each voice in music } catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return sequence; }
/** * Sets the instrument to be used for sequence playback. This implicitly loads the given * instrument. * * @param instr The instrument to be used for sequence playback. */ public void setInstrument(Instrument instr) throws MidiUnavailableException { MidiSystem.getSynthesizer().loadInstrument(instr); instrument = instr; }
public void run() { try { if (waitfor != null) waitfor.join(); Resource res = Loading.waitforint(this.res); try { seq = MidiSystem.getSequencer(false); synth = MidiSystem.getSynthesizer(); seq.open(); seq.setSequence(res.layer(Resource.Music.class).seq); synth.open(); seq.getTransmitter().setReceiver(synth.getReceiver()); } catch (MidiUnavailableException e) { return; } catch (InvalidMidiDataException e) { return; } catch (IllegalArgumentException e) { /* The soft synthesizer appears to be throwing * non-checked exceptions through from the sampled * audio system. Ignore them and only them. */ if (e.getMessage().startsWith("No line matching")) return; throw (e); } seq.addMetaEventListener( new MetaEventListener() { public void meta(MetaMessage msg) { debug("Meta " + msg.getType()); if (msg.getType() == 47) { synchronized (Player.this) { done = true; Player.this.notifyAll(); } } } }); do { debug("Start loop"); done = false; seq.start(); synchronized (this) { while (!done) this.wait(); } seq.setTickPosition(0); } while (loop); } catch (InterruptedException e) { } finally { try { debug("Exit player"); if (seq != null) seq.close(); try { if (synth != null) synth.close(); } catch (Throwable e2) { if (e2 instanceof InterruptedException) { /* XXX: There appears to be a bug in Sun's * software MIDI implementation that throws back * an unchecked InterruptedException here when two * interrupts come close together (such as in the * case when the current player is first stopped, * and then another started immediately afterwards * on a new song before the first one has had time * to terminate entirely). */ } else { throw (new RuntimeException(e2)); } } } finally { synchronized (Music.class) { if (player == this) player = null; } } } }