Exemple #1
1
 /**
  * Loads a sequence from an input stream. Returns null if an error occurs.
  *
  * @param is
  * @return
  */
 public Sequence getSequence(InputStream is) {
   try {
     if (!is.markSupported()) {
       is = new BufferedInputStream(is);
     }
     Sequence s = MidiSystem.getSequence(is);
     is.close();
     return s;
   } catch (InvalidMidiDataException ex) {
     ex.printStackTrace();
     return null;
   } catch (IOException ex) {
     ex.printStackTrace();
     return null;
   }
 }
Exemple #2
0
  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;
  }
Exemple #3
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();
    }
  }
Exemple #4
0
  public void go() {
    setUpGui();

    try {

      Sequencer sequencer = MidiSystem.getSequencer();
      sequencer.open();
      // make a sequencer and open
      sequencer.addControllerEventListener(m1, new int[] {127});
      Sequence seq = new Sequence(Sequence.PPQ, 4);
      Track track = seq.createTrack();

      int r = 0;
      for (int i = 0; i < 300; i += 4) {

        r = (int) ((Math.random() * 50) + 1);
        track.add(makeEvent(144, 1, r, 100, i));
        track.add(makeEvent(176, 1, 127, 0, i));
        track.add(makeEvent(128, 1, r, 100, i + 2));
      } // end loop

      sequencer.setSequence(seq);
      sequencer.start();
      sequencer.setTempoInBPM(120);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  } // close method
 public MIDIReader(String filename) {
   this.filename = filename;
   try {
     this.recebedor = MidiSystem.getReceiver();
     this.sequencia = MidiSystem.getSequence(new File(filename));
     this.tempoProcessor = new MidiUtils.TempoCache(sequencia);
     this.player = MidiSystem.getSequencer(true);
     this.player.setSequence(sequencia);
     this.player.open();
     this.interval = 0.5f;
     this.loadNotes();
     this.duration = this.getRealDuration();
   } catch (Exception ex) {
     Utilidades.alertar(ex.getMessage());
   }
 }
Exemple #6
0
 {
   try {
     sq = MidiSystem.getSequencer();
   } catch (MidiUnavailableException e) {
     e.printStackTrace();
   }
 }
Exemple #7
0
  /**
   * Exports to a file.
   *
   * @param outputFileName The output file name
   * @throws InvalidFileFormatException If the file name doesn't end in .mid or .midi
   */
  public void exportToFile(String outputFileName) throws InvalidFileFormatException {
    // Check for a valid file format.
    if (!outputFileName.endsWith(".mid") && !outputFileName.endsWith(".midi")) {
      String msg = "File names must end in .mid or .midi";
      throw new InvalidFileFormatException(msg);
    }

    // Find a supported file type, and export the file.
    int[] types = MidiSystem.getMidiFileTypes(sequence);
    try {
      File outputFile = new File(outputFileName);
      MidiSystem.write(sequence, types[0], outputFile);
    } catch (IOException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
  }
 public void play() {
   try {
     Sequencer player = MidiSystem.getSequencer();
     System.out.println("Successfully got a sequencer");
   } catch (MidiUnavailableException ex) {
     System.out.println("Bummer");
   }
 }
Exemple #9
0
 /** Creates a new MidiPlayer object. */
 public MidiPlayer() {
   try {
     sequencer = MidiSystem.getSequencer();
     sequencer.open();
     sequencer.addMetaEventListener(this);
   } catch (MidiUnavailableException ex) {
     sequencer = null;
   }
 }
 public MidiViewImpl() {
   try {
     this.synth = MidiSystem.getSynthesizer();
     this.receiver = synth.getReceiver();
     this.synth.open();
   } catch (MidiUnavailableException e) {
     e.printStackTrace();
   }
 }
 /**
  * @param key is the note that this starts with. 60 is middle C.
  * @param tempo is measured in beats per second
  */
 public MidiFileGenerator(int key, int tempo, int resolution)
     throws MidiUnavailableException, InvalidMidiDataException {
   this.resolution = resolution;
   Sequence sequence = new Sequence(Sequence.PPQ, resolution);
   track = sequence.createTrack();
   // makeSong(key);
   sequencer = MidiSystem.getSequencer();
   sequencer.open();
   sequencer.setSequence(sequence);
   sequencer.setTempoInBPM(tempo);
 }
Exemple #12
0
 public boolean saveMidiFile(File file) {
   try {
     int[] fileTypes = MidiSystem.getMidiFileTypes(sequence);
     if (fileTypes.length == 0) {
       System.out.println("Can't save sequence");
       return false;
     } else {
       if (MidiSystem.write(sequence, fileTypes[0], file) == -1) {
         throw new IOException("Problems writing to file");
       }
       return true;
     }
   } catch (SecurityException ex) {
     ex.printStackTrace();
     return false;
   } catch (Exception ex) {
     ex.printStackTrace();
     return false;
   }
 }
  public void setUpMidi() {
    try {
      sequencer = MidiSystem.getSequencer();
      sequencer.open();
      sequence = new Sequence(Sequence.PPQ, 4);
      track = sequence.createTrack();
      sequencer.setTempoInBPM(120);

    } catch (Exception e) {
      e.printStackTrace();
    }
  } // close method
  /** Carrega a seqüência do sistema de arquivos. Retorna null se um erro ocorrer. */
  public Sequence getSequence(String name) {

    String filename = "/recursos/sons/" + name;
    try {
      return MidiSystem.getSequence(getClass().getResource((filename)));
    } catch (InvalidMidiDataException ex) {
      ex.printStackTrace();
      return null;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    }
  }
Exemple #15
0
  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;
  }
Exemple #16
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();
  }
Exemple #17
0
  public void setup() {
    parser = new MidiParser();
    listener = new StaccatoParserListener();
    player = new Player();

    parser.addParserListener(listener);

    try {
      File midiFile =
          new File(
              dataPath(
                  "/Users/fbonnamy/Documents/pro/WIW/MusicalLetter/prototypage/MidiReader/data/WIW_NOEL_test_midi.mid"));
      parser.parse(MidiSystem.getSequence(midiFile));
      Pattern staccatoPattern = listener.getPattern();
      System.out.println(staccatoPattern);

      player.play(staccatoPattern);
    } catch (Exception e) {
    }
  }
Exemple #18
0
 private static void playMidi(String name, boolean loop, double volume)
     throws MidiUnavailableException, FileNotFoundException, IOException,
         InvalidMidiDataException {
   // Obtains the default Sequencer connected to a default device.
   Sequencer sequencer = MidiSystem.getSequencer();
   // Opens the device, indicating that it should now acquire any system resources it requires and
   // become operational.
   sequencer.open();
   // create a stream from a file
   InputStream is = new BufferedInputStream(new FileInputStream(new File(path + name)));
   // Sets the current sequence on which the sequencer operates.
   // The stream must point to MIDI file data.
   sequencer.setSequence(is);
   // Set looping
   if (loop) {
     sequencer.setLoopCount(LOOP_CONTINUOUSLY);
   }
   // Starts playback of the MIDI data in the currently loaded sequence.
   sequencer.start();
   midiMap.put(name, sequencer);
 }
Exemple #19
0
  /** 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 void actionPerformed(ActionEvent ev) {

      try {

        // make (and open) a sequencer, make a sequence and track

        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();

        sequencer.addControllerEventListener(myPanel, new int[] {127});
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();

        // now make two midi events (containing a midi message)

        for (int i = 0; i < 100; i += 4) {

          int rNum = (int) ((Math.random() * 50) + 1);
          if (rNum < 38) { // so now only do it if num <38 (75% of the time)

            track.add(makeEvent(144, 1, rNum, 100, i));

            track.add(makeEvent(176, 1, 127, 0, i));

            track.add(makeEvent(128, 1, rNum, 100, i + 2));
          }
        } // end loop

        // add the events to the track
        // add the sequence to the sequencer, set timing, and start

        sequencer.setSequence(seq);

        sequencer.start();
        sequencer.setTempoInBPM(220);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    } // close actionperformed
  public void play(int instrument, int note) {

    try {

      Sequencer player = MidiSystem.getSequencer();
      player.open();

      Sequence seq = new Sequence(Sequence.PPQ, 4);
      Track track = seq.createTrack();

      // MidiEvent event = null;

      ShortMessage first = new ShortMessage();
      first.setMessage(192, 1, instrument, 0);
      MidiEvent changeInstrument = new MidiEvent(first, 1);
      track.add(changeInstrument);

      ShortMessage a = new ShortMessage();
      a.setMessage(144, 1, note, 100);
      MidiEvent noteOn = new MidiEvent(a, 1);
      track.add(noteOn);

      ShortMessage b = new ShortMessage();
      b.setMessage(128, 1, note, 100);
      MidiEvent noteOff = new MidiEvent(b, 16);
      track.add(noteOff);
      player.setSequence(seq);
      player.start();

      Thread.sleep(2000);
      player.close();
      System.exit(0);

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
    }
  } // close play
  private synchronized void startMidi(InputStream bis, InputStream in)
      throws InvalidMidiDataException, MidiUnavailableException {

    Sequencer sequencer = null;
    Info info = null;

    // sequencer = MidiSystem.getSequencer( null );
    sequencer = MidiSystem.getSequencer();
    sequencer.open();
    try {
      sequencer.setSequence(bis);
    } catch (IOException e) {
      throw new InvalidMidiDataException(e.getMessage());
    }

    info = new Info(sequencer, in, null);

    infos.addElement(info);

    // fix for bug 4302884: Audio device is not released when AudioClip stops
    sequencer.addMetaEventListener(info);

    sequencer.start();
  }
  public void los() {
    guiErstellen();

    try {

      // einen Sequencer erzeugen (und öffnen),
      // eine Sequence und einen Track erzeugen

      Sequencer sequencer = MidiSystem.getSequencer();
      sequencer.open();
      sequencer.addControllerEventListener(ml, new int[] {127});
      Sequence seq = new Sequence(Sequence.PPQ, 4);
      Track track = seq.createTrack();

      // jetzt werden MidiEvents (die eine
      // MidiMessage enthalten) erzeugt

      int r = 0;
      for (int i = 0; i < 60; i += 4) {
        r = (int) ((Math.random() * 50) + 1);
        track.add(eventErzeugen(144, 1, r, 100, i));
        track.add(eventErzeugen(176, 1, 127, 0, i));
        track.add(eventErzeugen(128, 1, r, 100, i + 2));
      } // Ende der for-Schleife

      // Hinzufügen der Events zum Track und der Sequence
      // zum Sequencer, Setzen der Zeiten und Starten

      sequencer.setSequence(seq);
      sequencer.start();
      sequencer.setTempoInBPM(120);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  } // Methode los schließen
  /** Open an audio channel. */
  public synchronized void openChannel(InputStream in) {

    if (DEBUG) {
      System.out.println("AudioDevice: openChannel");
      System.out.println("input stream =" + in);
    }

    Info info = null;

    // is this already playing?  if so, then just return
    for (int i = 0; i < infos.size(); i++) {
      info = (AudioDevice.Info) infos.elementAt(i);
      if (info.in == in) {

        return;
      }
    }

    AudioInputStream as = null;

    if (in instanceof AudioStream) {

      if (((AudioStream) in).midiformat != null) {

        // it's a midi file
        try {
          startMidi(((AudioStream) in).stream, in);
        } catch (Exception e) {
          return;
        }

      } else if (((AudioStream) in).ais != null) {

        // it's sampled audio
        try {
          startSampled(((AudioStream) in).ais, in);
        } catch (Exception e) {
          return;
        }
      }
    } else if (in instanceof AudioDataStream) {
      if (in instanceof ContinuousAudioDataStream) {
        try {
          AudioInputStream ais =
              new AudioInputStream(
                  in, ((AudioDataStream) in).getAudioData().format, AudioSystem.NOT_SPECIFIED);
          startSampled(ais, in);
        } catch (Exception e) {
          return;
        }
      } else {
        try {
          AudioInputStream ais =
              new AudioInputStream(
                  in,
                  ((AudioDataStream) in).getAudioData().format,
                  ((AudioDataStream) in).getAudioData().buffer.length);
          startSampled(ais, in);
        } catch (Exception e) {
          return;
        }
      }
    } else {
      BufferedInputStream bis = new BufferedInputStream(in, 1024);

      try {

        try {
          as = AudioSystem.getAudioInputStream(bis);
        } catch (IOException ioe) {
          return;
        }

        startSampled(as, in);

      } catch (UnsupportedAudioFileException e) {

        try {
          try {
            MidiFileFormat mff = MidiSystem.getMidiFileFormat(bis);
          } catch (IOException ioe1) {
            return;
          }

          startMidi(bis, in);

        } catch (InvalidMidiDataException e1) {

          // $$jb:08.01.99: adding this section to make some of our other
          // legacy classes work.....
          // not MIDI either, special case handling for all others

          AudioFormat defformat =
              new AudioFormat(AudioFormat.Encoding.ULAW, 8000, 8, 1, 1, 8000, true);
          try {
            AudioInputStream defaif =
                new AudioInputStream(bis, defformat, AudioSystem.NOT_SPECIFIED);
            startSampled(defaif, in);
          } catch (UnsupportedAudioFileException es) {
            return;
          } catch (LineUnavailableException es2) {
            return;
          }

        } catch (MidiUnavailableException e2) {

          // could not open sequence
          return;
        }

      } catch (LineUnavailableException e) {

        return;
      }
    }

    // don't forget adjust for a new stream.
    notify();
  }
Exemple #25
0
 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;
       }
     }
   }
 }
  public static void main(String[] args) throws Exception {

    InputStream sb = getInputStream("ding.sf2");
    soundbank = MidiSystem.getSoundbank(sb);
    sb.close();

    InputStream si = getInputStream("expresso.mid");
    sequence = MidiSystem.getSequence(si);
    si.close();

    AudioFormat format;
    Map<String, Object> info = new HashMap<String, Object>();
    {
      format = new AudioFormat(22050, 16, 2, true, false);
      test(format, info);
      format = new AudioFormat(44100, 16, 2, true, false);
      test(format, info);
    }
    {
      format = new AudioFormat(44100, 8, 2, true, false);
      test(format, info);
      format = new AudioFormat(44100, 16, 2, true, false);
      test(format, info);
      format = new AudioFormat(44100, 24, 2, true, false);
      test(format, info);
    }
    {
      format = new AudioFormat(44100, 16, 1, true, false);
      test(format, info);
      format = new AudioFormat(44100, 16, 2, true, false);
      test(format, info);
    }
    {
      format = new AudioFormat(44100, 16, 2, true, false);

      info.clear();
      info.put("control rate", 100f);
      test(format, info);
      info.clear();
      info.put("control rate", 147f);
      test(format, info);
    }
    {
      format = new AudioFormat(44100, 16, 2, true, false);

      info.clear();
      info.put("interpolation", "point");
      test(format, info);
      info.clear();
      info.put("interpolation", "linear");
      test(format, info);
      info.clear();
      info.put("interpolation", "cubic");
      test(format, info);
    }
    {
      format = new AudioFormat(44100, 16, 2, true, false);
      info.clear();
      info.put("max polyphony", 4);
      test(format, info);
      info.clear();
      info.put("max polyphony", 16);
      test(format, info);
      info.clear();
    }
  }
  private void process() throws InvalidMidiDataException, IOException, JAXBException {

    Sequence orchestraSequence = MidiSystem.getSequence(inputFile);

    Sequence masterSequence = new Sequence(Sequence.PPQ, resolution);

    //  the orchestra tracks
    for (int i = 0; i < orchestraSequence.getTracks().length; i++) {
      masterSequence =
          TrackMerger.process(
              masterSequence, orchestraSequence, new int[] {i}, -1, null, loggingHandler); //
    }

    // This is a hack....to make the track 0 as long as the whole sequence
    double rawSeqLen = masterSequence.getTickLength();
    double quarterLen = masterSequence.getResolution();
    double barLen = 4 * quarterLen;
    long fullSeqLen = (long) (barLen * (Math.ceil((rawSeqLen + quarterLen) / barLen)));
    masterSequence.getTracks()[0].add(newEndOfTrackMessage(fullSeqLen));

    // add track 5; the metronome track
    masterSequence = MetronomeCreator.process(masterSequence, 0, loggingHandler);

    System.out.println("** Track 0 length " + masterSequence.getTracks()[0].ticks());
    System.out.println("** Sequence length " + masterSequence.getTickLength());

    ChannelCleaner sequenceImporter = new ChannelCleaner(masterSequence, loggingHandler);
    masterSequence = sequenceImporter.getResult();

    // Write the file to disk
    MidiSystem.write(masterSequence, 1, outputMidiFile);
    System.out.println("############ Midi file is: " + outputMidiFile.getCanonicalPath());

    // ----------------------------------------------------------------------------------------
    // create the appropriate song object
    Song songObject = new Song();
    songObject.setName(description);

    MasterTrack mastertrack = songObject.createMastertrack();
    mastertrack.setSequencefile(outputMidiFile.getName());
    mastertrack.setName(sequenceImporter.getTrackName(0));
    mastertrack.setMidiTrackIndex(0);
    mastertrack.setMidiChannel(sequenceImporter.getChannel(0));

    // create a super track that will collect all orchestra tracs
    MidiSynthesizerTrack orchestraSuperTrack = new MidiSynthesizerTrack();
    orchestraSuperTrack.setName("Orchester");
    mastertrack.addSubtrack(orchestraSuperTrack);
    BuiltinSynthesizer OrchestraSynt = new BuiltinSynthesizer();
    OrchestraSynt.setSoundbankfile("../Schickardt.sf2");
    orchestraSuperTrack.setSynthesizer(OrchestraSynt);

    // create a super track that will collect the voices tracs
    MidiSynthesizerTrack voicesSuperTrack = new MidiSynthesizerTrack();
    voicesSuperTrack.setName("Voices");
    mastertrack.addSubtrack(voicesSuperTrack);
    BuiltinSynthesizer voicesSynt = new BuiltinSynthesizer();
    voicesSynt.setSoundbankfile("../StringPiano.sf2");
    voicesSuperTrack.setSynthesizer(voicesSynt);

    // link all the orchestra tracks
    int orchestraBase = 1; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    int orchestraEnd = 2; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    for (int i = orchestraBase; i <= orchestraEnd; i++) {
      MidiTrack songTrack = new MidiTrack();
      songTrack.setName(sequenceImporter.getTrackName(i));
      songTrack.setMidiTrackIndex(i);
      songTrack.setMidiChannel(sequenceImporter.getChannel(i));
      songTrack.setInstrumentDescription(sequenceImporter.getInstrumentDescription(i));
      orchestraSuperTrack.addSubtrack(songTrack);
    }

    MidiTrack newSongTrack;
    int voiceBase = 3;
    // -- Diskant
    newSongTrack = new MidiTrack();
    newSongTrack.setName("Flute 1");
    newSongTrack.setMidiTrackIndex(voiceBase);
    newSongTrack.setMidiChannel(0);
    newSongTrack.setInstrumentDescription("Piano");
    newSongTrack.setMute(true);
    voicesSuperTrack.addSubtrack(newSongTrack);
    // -- Bass
    voiceBase++; // 4
    newSongTrack = new MidiTrack();
    newSongTrack.setName("Flute 2");
    newSongTrack.setMidiTrackIndex(voiceBase);
    newSongTrack.setMidiChannel(1);
    newSongTrack.setInstrumentDescription("Piano");
    newSongTrack.setMute(true);
    voicesSuperTrack.addSubtrack(newSongTrack);

    // -- Metronome
    voiceBase++; // 5
    newSongTrack = new MidiTrack();
    newSongTrack.setName("Metronome");
    newSongTrack.setMidiTrackIndex(voiceBase);
    newSongTrack.setMidiChannel(9);
    newSongTrack.setInstrumentDescription("Metronome");
    newSongTrack.setMute(true);
    voicesSuperTrack.addSubtrack(newSongTrack);

    songObject.marshal(new FileOutputStream(outputSongFile));
    System.out.println("############ Song file is: " + outputSongFile.getCanonicalPath());
  }
Exemple #28
0
  public void play(String name, String version, String vendor, String desc) throws Exception {
    Info port = null;
    for (Info info : MidiSystem.getMidiDeviceInfo()) {
      if (name == null && version == null && vendor == null && desc == null) {
        System.err.println(
            "At least one of name, version, vendor, or description must be specified.");
        break;
      }
      if (name != null && !info.getName().equals(name)) {
        continue;
      }
      if (vendor != null && !info.getVendor().equals(vendor)) {
        continue;
      }
      if (version != null && !info.getVersion().equals(version)) {
        continue;
      }
      if (desc != null && !info.getDescription().equals(desc)) {
        continue;
      }
      try (MidiDevice dev = MidiSystem.getMidiDevice(info)) {
        Receiver r = null;
        try {
          r = dev.getReceiver();
        } catch (Exception e) {
          r = null;
        }
        if (r == null) {
          continue;
        }
      }
      if (port != null) {
        System.err.println(
            "Multiple MIDI ports match the given parameters. Please be more specific.");
        port = null;
        break;
      }
      port = info;
      continue;
    }
    if (port == null) {
      System.err.println("Unable to locate MIDI port");
      System.err.println("Available ports:");
      for (Info info : MidiSystem.getMidiDeviceInfo()) {
        try (MidiDevice dev = MidiSystem.getMidiDevice(info)) {
          Receiver r = null;
          try {
            r = dev.getReceiver();
          } catch (Exception e) {
            r = null;
          }
          if (r == null) {
            continue;
          }
        }

        System.out.println(
            "Device [name="
                + info.getName()
                + ", version="
                + info.getVersion()
                + ", vendor="
                + info.getVendor()
                + ", desc="
                + info.getDescription()
                + "]");
      }
      return;
    }

    System.out.println(
        "Using device [name="
            + port.getName()
            + ", version="
            + port.getVersion()
            + ", vendor="
            + port.getVendor()
            + ", desc="
            + port.getDescription()
            + "]");

    try (MidiDevice dev = MidiSystem.getMidiDevice(port)) {
      int channel = CHANNEL_RAW_STEREO;
      dev.open();

      try (Receiver rx = dev.getReceiver()) {
        rxCleanup = rx;
        try (DataInputStream dis = new DataInputStream(new FileInputStream(ymz))) {
          resetController(rx, channel, registers);
          long startTime = System.nanoTime();

          // read a buffer
          long prevClock = 0;
          while (true) {
            long clock = dis.readLong();
            byte register = dis.readByte();
            byte value = dis.readByte();
            if (prevClock != clock) {
              sendAll(rx, channel, registers);
              prevClock = clock;
            }
            sleepUntil(startTime, clock);
            System.out.println(
                "Clock: " + clock + " register: " + register + ", value: " + (value & 0xff));
            if (register < 0 || register > 13) {
              System.err.println("Invalid register " + register + " found, ignoring.");
              continue;
            }
            registers[register] = value;
          }
        } catch (EOFException e) {
          System.err.println("EOF reached");
        } finally {
          resetController(rx, channel, registers);
          rxCleanup = null;
        }
      }
    }
  }