Beispiel #1
0
 {
   try {
     sq = MidiSystem.getSequencer();
   } catch (MidiUnavailableException e) {
     e.printStackTrace();
   }
 }
Beispiel #2
0
  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;
  }
Beispiel #3
0
  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();
    }
  }
Beispiel #4
0
  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();
    }
  }
Beispiel #5
0
  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 + ")");
    }
  }
Beispiel #6
0
 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();
   }
 }
Beispiel #8
0
 /** 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 MidiReceiverForTransmitterDevice() {
      parser = new MidiParser();
      renderer = new MusicStringRenderer();
      parser.addParserListener(renderer);

      try {
        sequencer = MidiSystem.getSequencer();
        sequencerReceiver = sequencer.getReceiver();
      } catch (MidiUnavailableException e) {
        e.printStackTrace();
      }
    }
Beispiel #10
0
 // mergePlayEmptyTest(): m1 and/or m2 empty
 @Test
 public void mergePlayEmptyTest() {
   Merge a = new Merge(new Rest(0), new Rest(0));
   try {
     SequencePlayer player = new SequencePlayer(140, 12);
     a.play(player, 0);
     assertEquals("Meta event: END_OF_TRACK Tick: 0\n", player.toString());
   } catch (MidiUnavailableException mue) {
     mue.printStackTrace();
   } catch (InvalidMidiDataException imde) {
     imde.printStackTrace();
   }
 }
Beispiel #11
0
 public static MidiDevice getMidiDevice(MidiDevice.Info deviceInfo)
     throws MidiUnavailableException {
   try {
     return MidiSystem.getMidiDevice(deviceInfo);
   } catch (IllegalArgumentException e) {
     // the device does not exist anymore -
     // this seems to be a bug because MidiUnavailableException should
     // be thrown instead
     MidiUnavailableException m = new MidiUnavailableException();
     m.initCause(e);
     throw m;
   }
 }
    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.");
	}
    }
Beispiel #13
0
  private void openSequencer() {
    if (getSequencer() == null) {
      throw new JFugueException(JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED);
    }

    // Open the sequencer, if it is not already open
    if (!getSequencer().isOpen()) {
      try {
        getSequencer().open();
      } catch (MidiUnavailableException e) {
        throw new JFugueException(
            JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED_WITH_EXCEPTION + e.getMessage());
      }
    }
  }
Beispiel #14
0
 // musicPlayLargeCaseTest(): row row row your boat
 @Test
 public void musicPlayLargeCaseTest() {
   try {
     SequencePlayer player = new SequencePlayer(140, 12);
     rowRowRowYourBoat.play(player, .125);
     player.play();
     Thread.sleep(10000);
   } catch (MidiUnavailableException mue) {
     mue.printStackTrace();
   } catch (InvalidMidiDataException imde) {
     imde.printStackTrace();
   } catch (InterruptedException ie) {
     ie.printStackTrace();
   }
 }
Beispiel #15
0
  public void playSequenceFromJFugueString(String noteString, int instrument) {

    initialize();
    try {
      sequencer.open();
      synthesizer.open();
    } catch (MidiUnavailableException e) {
      e.printStackTrace();
    }

    noteString = "I[" + instrument + "] " + noteString;
    player = new Player(sequencer);
    Pattern pattern = new Pattern(noteString);
    PlayerThread thread = new PlayerThread(player, pattern);
    thread.start();
  }
Beispiel #16
0
 /**
  * Instantiates a new Player object, which is used for playing music. The <code>connected</code>
  * parameter is passed directly to MidiSystem.getSequencer. Pass false when you do not want to
  * copy a live synthesizer - for example, if your Player is on a server, and you don't want to
  * create new synthesizers every time the constructor is called.
  */
 public Player(boolean connected) {
   try {
     // Get default sequencer.
     setSequencer(MidiSystem.getSequencer(connected)); // use non
     // connected
     // sequencer so
     // no copy of
     // live
     // synthesizer
     // will be
     // created.
   } catch (MidiUnavailableException e) {
     throw new JFugueException(
         JFugueException.SEQUENCER_DEVICE_NOT_SUPPORTED_WITH_EXCEPTION + e.getMessage());
   }
   initParser();
 }
Beispiel #17
0
 /**
  * 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);
 }
  /** Method to get all available midi ports and add them to the corresponding device list. */
  private void getAvailablePorts() {
    javax.sound.midi.MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < infos.length; i++) {
      try {
        javax.sound.midi.MidiDevice theDevice = MidiSystem.getMidiDevice(infos[i]);

        if (theDevice instanceof javax.sound.midi.Sequencer) {
          // Ignore this device as it's a sequencer
        } else if (theDevice.getMaxReceivers() != 0) {
          midiOutDevices.add(theDevice);
        } else if (theDevice.getMaxTransmitters() != 0) {
          midiInputDevices.add(theDevice);
        }
      } catch (MidiUnavailableException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #19
0
 // parallelPlayEqualsTest(): m1 = m2
 @Test
 public void parallelPlayEqualsTest() {
   Parallel a = new Parallel(new Note(1, new Pitch('C')), new Note(1, new Pitch('C')));
   try {
     SequencePlayer player = new SequencePlayer(140, 12);
     a.play(player, 0);
     assertEquals(
         "Event: NOTE_ON  Pitch: 60  Tick: 0\n"
             + "Event: NOTE_ON  Pitch: 60  Tick: 0\n"
             + "Event: NOTE_OFF Pitch: 60  Tick: 12\n"
             + "Event: NOTE_OFF Pitch: 60  Tick: 12\n"
             + "Meta event: END_OF_TRACK Tick: 12\n",
         player.toString());
   } catch (MidiUnavailableException mue) {
     mue.printStackTrace();
   } catch (InvalidMidiDataException imde) {
     imde.printStackTrace();
   }
 }
Beispiel #20
0
 // chordPlayDifferentDurationsTest(): m1.duration != m2.duration
 @Test
 public void chordPlayDifferentDurationsTest() {
   Chord a = new Chord(new Note(1, new Pitch('D')), new Note(2, new Pitch('C')));
   try {
     SequencePlayer player = new SequencePlayer(140, 12);
     a.play(player, 0);
     assertEquals(
         "Event: NOTE_ON  Pitch: 62  Tick: 0\n"
             + "Event: NOTE_ON  Pitch: 60  Tick: 0\n"
             + "Event: NOTE_OFF Pitch: 62  Tick: 12\n"
             + "Event: NOTE_OFF Pitch: 60  Tick: 24\n"
             + "Meta event: END_OF_TRACK Tick: 24\n",
         player.toString());
   } catch (MidiUnavailableException mue) {
     mue.printStackTrace();
   } catch (InvalidMidiDataException imde) {
     imde.printStackTrace();
   }
 }
Beispiel #21
0
 public void playMusic() {
   if (judgetone == true) {
     System.out.print("Make Cheerful Song.\r\n");
     try {
       sequence = new Sequence(Sequence.PPQ, 24, 3);
       MelodyMaker.setCheerfulMelody(sequence, length, velocity);
       AccompanimentMaker.makeCheerfulAccompaniment(sequence, length, velocity);
       sequencer = MidiSystem.getSequencer();
       sequencer.open();
       sequencer.setSequence(sequence);
       sequencer.start();
       while (sequencer.isRunning()) Thread.sleep(100);
     } catch (InterruptedException e) {
       e.printStackTrace();
     } catch (MidiUnavailableException e) {
       e.printStackTrace();
     } catch (InvalidMidiDataException e) {
       e.printStackTrace();
     } finally {
       if (sequencer != null && sequencer.isOpen()) sequencer.close();
     }
   } else if (judgetone == false) {
     System.out.print("Make Gloomy Song.\r\n");
     try {
       sequence = new Sequence(Sequence.PPQ, 24, 3);
       MelodyMaker.setGloomyMelody(sequence, length, velocity);
       AccompanimentMaker.makeGloomyAccompaniment(sequence, length, velocity);
       sequencer = MidiSystem.getSequencer();
       sequencer.open();
       sequencer.setSequence(sequence);
       sequencer.start();
       while (sequencer.isRunning()) Thread.sleep(100);
     } catch (InterruptedException e) {
       e.printStackTrace();
     } catch (MidiUnavailableException e) {
       e.printStackTrace();
     } catch (InvalidMidiDataException e) {
       e.printStackTrace();
     } finally {
       if (sequencer != null && sequencer.isOpen()) sequencer.close();
     }
   }
 }
Beispiel #22
0
  /**
   * Sets up the sequencer with a given sequence.
   *
   * @param sequenceToUse
   * @throws MidiUnavailableException
   */
  private void setUpSequencer() throws MidiUnavailableException {
    // First, get the system's default sequencer.
    try {
      sequencer = MidiSystem.getSequencer();
    } catch (MidiUnavailableException ex) {
      // Something went wrong.
      ex.printStackTrace();
      System.exit(1);
    }

    // If there is none, throw an exception.
    if (sequencer == null) {
      String msg = "Cannot find a sequencer";
      throw new MidiUnavailableException(msg);
    }

    // Set up the transmitter and receiver of the synth to play the song.
    linkTransmitterToReceiver();
  }
Beispiel #23
0
 // notePlayTest(): covers all partitions
 @Test
 public void notePlayTest() {
   Note shortNote = new Note(.5, new Pitch('A'));
   Note highNote = new Note(20, new Pitch('A')).transpose(20);
   try {
     SequencePlayer player = new SequencePlayer(140, 12);
     shortNote.play(player, 0);
     highNote.play(player, .5);
     assertEquals(
         "Event: NOTE_ON  Pitch: 69  Tick: 0\n"
             + "Event: NOTE_OFF Pitch: 69  Tick: 6\n"
             + "Event: NOTE_ON  Pitch: 89  Tick: 6\n"
             + "Event: NOTE_OFF Pitch: 89  Tick: 246\n"
             + "Meta event: END_OF_TRACK Tick: 246\n",
         player.toString());
   } catch (MidiUnavailableException mue) {
     mue.printStackTrace();
   } catch (InvalidMidiDataException imde) {
     imde.printStackTrace();
   }
 }
Beispiel #24
0
  /** @return The reciever associated with this lane */
  public Receiver getReceiver() {
    MidiDevice dev = ftw.getMidiDevice();

    if (dev == null) {
      return null;
    }

    try {
      // Jens:
      // return getTrack().getMidiDevice().getReceiver();
      Receiver r = ftw.getMidiDevice().getReceiver();
      if (r != null) {
        return new MonitorReceiver(midiMessageListeners, r);
      } else {
        return null;
      }
    } catch (MidiUnavailableException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
  /** Fill MIDI devices comboboxes. */
  public void updateMidiDevices(MidiDevice.Info[] midiDeviceInfo) {
    _midiInComboBox.removeAllItems();
    _midiOutComboBox.removeAllItems();

    try {
      int n = midiDeviceInfo.length;
      for (int i = 0; i < n; i++) {
        MidiDevice midiDevice = MidiSystem.getMidiDevice(midiDeviceInfo[i]);

        if (midiDevice.getMaxTransmitters() != 0) {
          _midiInComboBox.addItem(midiDeviceInfo[i]);
        }
        if (midiDevice.getMaxReceivers() != 0) {
          _midiOutComboBox.addItem(midiDeviceInfo[i]);
        }
      }

      _midiInComboBox.setSelectedIndex(-1);
      _midiOutComboBox.setSelectedIndex(-1);
    } catch (MidiUnavailableException exception) {
      System.out.println("MIDI device unavailable: " + exception.getMessage());
    }
  }
Beispiel #26
0
  /**
   * Transforms the Voices of the Piece into Pitches which are then subscribed according to timing
   * to an internal SequencePlayer, then plays that SequencePlayer to play the Piece out loud
   *
   * <p>Catches SequencePlayer Errors internally to avoid them being part of the ABCMusic's
   * responsibility
   *
   * <p>Note: because tempo must be converted to quarter notes, tempos that are not divisible by 4
   * will have rounding errors that propagate into the music itself, its fairly negligible, but it
   * exists.
   *
   * <p>Note: Assumes that 1/16 of the default note length is the shortest note that would be
   * desired to play, any note shorter will play for 1/16 of a default note duration
   */
  public void PlayMusic() {
    try {
      // Right now it converts bpm to be based on the number of 1/4 given how many L*Q notes exist
      // with the quantized time being
      int quartersPerMin = (getTempo() * getNoteLength()[0] * 4) / (getNoteLength()[1]);
      int ticksPerQuarter = (getNoteLength()[1] * 16) / (getNoteLength()[0] * 4);
      player = new SequencePlayer(quartersPerMin, ticksPerQuarter);
      // Figure out what the Key means, and keep it as a map to edit notes as they are added
      keySignature = getKeySignature();
      // Initialize the accidentals as none, then use that as what gets edited through a meter
      resetKeyAccidental();

      for (Iterator<Voice> i = VoicesList.iterator(); i.hasNext(); ) {
        int startTick = 0;
        for (Iterator<Bars> j = i.next().BarsList.iterator(); j.hasNext(); ) {
          for (Iterator<Meters> k = j.next().MetersList.iterator(); k.hasNext(); ) {
            for (Iterator<NoteToken> l = k.next().getElts().iterator(); l.hasNext(); ) {
              NoteToken workingNote = l.next();
              if (workingNote.getType() == Tokens.Type.CHORD) {
                int noteTicks = 0;
                for (int m = 0; m < workingNote.getElts().length; m++) {
                  Pitch newNote = constructNote(workingNote.getElts()[m]);
                  // Length of a note in terms of quarters
                  double noteLength =
                      ((double) workingNote.getElts()[m].getLength()[0]
                              / (double) workingNote.getElts()[m].getLength()[1])
                          * ((double) (getNoteLength()[0] * 4) / ((double) getNoteLength()[1]));
                  // Convert the quarters to valid ticks
                  noteTicks = (int) (noteLength * ticksPerQuarter);
                  player.addNote(newNote.toMidiNote(), startTick, noteTicks);
                }
                startTick += noteTicks;
              } else if (workingNote.getType() == Tokens.Type.REST) {
                // Don't need to make rests
                // Length of a note in terms of quarters
                double noteLength =
                    ((double) workingNote.getLength()[0] / (double) workingNote.getLength()[1])
                        * ((double) (getNoteLength()[0] * 4) / ((double) getNoteLength()[1]));
                // Convert the quarters to valid ticks
                // Add ticks for the rests skipping time
                int noteTicks = (int) (noteLength * ticksPerQuarter);
                startTick += noteTicks;
              } else {
                Pitch newNote = constructNote(workingNote);
                // Length of a note in terms of quarters
                double noteLength =
                    ((double) workingNote.getLength()[0] / (double) workingNote.getLength()[1])
                        * ((double) (getNoteLength()[0] * 4) / ((double) getNoteLength()[1]));
                // Convert the quarters to valid ticks
                int noteTicks = (int) (noteLength * ticksPerQuarter);
                player.addNote(newNote.toMidiNote(), startTick, noteTicks);
                startTick += noteTicks;
              }
            }
            // Reset Accidentals at the end of the Meter
            resetKeyAccidental();
          }
        }
      }
      // Play the finished SequencePlayer with all Voice there-in
      player.play();
      // Catch undesirable errors
    } catch (MidiUnavailableException e) {
      e.printStackTrace();
    } catch (InvalidMidiDataException e) {
      e.printStackTrace();
    }
  }