예제 #1
0
 /**
  * Constructor. It breaks a Song into its MidiEvent components, and adds them together in order to
  * create a MIDI file.
  *
  * @param song The song to export
  */
 public MidiExporter() {
   // Create the Sequence that will contain everything
   try {
     sequence = new Sequence(Sequence.PPQ, 2);
   } catch (InvalidMidiDataException ex) {
     ex.printStackTrace();
     System.exit(1);
   }
 }
  public static void render(OutputStream os, AudioFormat format, Map<String, Object> info)
      throws Exception {
    AudioSynthesizer synth = (AudioSynthesizer) new SoftSynthesizer();
    AudioInputStream stream = synth.openStream(format, info);
    Receiver recv = synth.getReceiver();
    Soundbank defsbk = synth.getDefaultSoundbank();
    if (defsbk != null) synth.unloadAllInstruments(defsbk);
    synth.loadAllInstruments(soundbank);

    double totalTime = 5;
    send(sequence, recv);

    long len = (long) (stream.getFormat().getFrameRate() * (totalTime + 4));
    stream = new AudioInputStream(stream, stream.getFormat(), len);

    long t = System.currentTimeMillis();
    AudioSystem.write(stream, AudioFileFormat.Type.WAVE, os);
    t = System.currentTimeMillis() - t;
    stream.close();
  }
예제 #3
0
  public static void main(String[] args) throws Exception {
    String portName = null;
    String portVersion = null;
    String portVendor = null;
    String portDesc = null;
    String ymzFilename = null;

    boolean invalid = true;
    LinkedList<String> list = new LinkedList<>(Arrays.asList(args));
    argCheck:
    while (!list.isEmpty()) {
      String arg = list.removeFirst();
      switch (arg) {
        case "--midi-name":
          if (list.isEmpty()) {
            break argCheck;
          }
          portName = list.removeFirst();
          break;
        case "--midi-version":
          if (list.isEmpty()) {
            break argCheck;
          }
          portVersion = list.removeFirst();
          break;
        case "--midi-vendor":
          if (list.isEmpty()) {
            break argCheck;
          }
          portVendor = list.removeFirst();
          break;
        case "--midi-desc":
          if (list.isEmpty()) {
            break argCheck;
          }
          portDesc = list.removeFirst();
          break;
        default:
          ymzFilename = arg;
          invalid = false;
          break argCheck;
      }
    }

    if (invalid || !(list.isEmpty())) {
      usage();
      System.exit(1);
    }

    File input = new File(ymzFilename);
    YMZPlayer player = new YMZPlayer(input);
    player.play(portName, portVersion, portVendor, portDesc);
  }
예제 #4
0
  private void sleepUntil(long startTime, long clock) throws InterruptedException {
    // convert clock to timestamp in nanos

    long targetTime = (NS_PER_CLOCK * clock) + startTime;
    long totalTime = targetTime - System.nanoTime();
    if (totalTime < 0L) {
      return;
    }
    long millis = totalTime / 1000000L;
    long nanos = totalTime % 1000000L;

    Thread.sleep(millis, (int) nanos);
  }
예제 #5
0
  /**
   * Create the MidiEvent for a note, given the data.
   *
   * @param command The command value for the ShortMessage
   * @param note The MIDI value for the note to be played
   * @param eventTime When this event should occur
   * @param velocity The velocity of this note
   * @return The MidiEvent for the note
   */
  private MidiEvent createNoteEvent(int command, int note, int eventTime, int velocity) {
    // Create the message and set its parameters to the ones given.
    ShortMessage message = new ShortMessage();
    try {
      message.setMessage(command, 0, note, velocity);
    } catch (InvalidMidiDataException ex) {
      // Something went wrong.
      ex.printStackTrace();
      System.exit(1);
    }

    // Create the MidiEvent and return it.
    return new MidiEvent(message, eventTime);
  }
예제 #6
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);
    }
  }
예제 #7
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();
  }
예제 #8
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);
    }
  }
예제 #9
0
  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
예제 #10
0
  public boolean writeSequence(NoteList noteList) {

    this.noteList = noteList;

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    if (!buildNoteSequence()) return false;

    try {
      sequence = new Sequence(Sequence.PPQ, 10);
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }

    track = sequence.createTrack();
    startTime = System.currentTimeMillis();

    // add a program change right at the beginning of
    // the track for the current instrument

    createEvent(PROGRAM, cc.program + 1, 1);

    for (int i = 0; i < noteSequence.size(); i++) {
      noteSequenceElement = noteSequence.get(i);
      if (noteSequenceElement.state == ON)
        if (!createEvent(NOTEON, noteSequenceElement.note, noteSequenceElement.tick)) return false;
      if (noteSequenceElement.state == OFF)
        if (!createEvent(NOTEOFF, noteSequenceElement.note, noteSequenceElement.tick)) return false;
    }
    return true;
  }
 public static InputStream getInputStream(String filename) throws IOException {
   File file = new File(System.getProperty("test.src", "."), filename);
   FileInputStream fis = new FileInputStream(file);
   return new BufferedInputStream(fis);
 }
예제 #12
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;
        }
      }
    }
  }