10 January, 2008

Simple Java MIDI synthesizer sample

Another multi-media sample - simplest Java MIDI synthesizer.


MidiSynthesizerSample.java

import javax.sound.midi.*;
 
public class MidiSynthesizerSample {
  public static void main(String[] args) {
      int[] notes = new int[]{60, 62, 64, 65, 67, 69, 71, 72, 72, 71, 69, 67, 65, 64, 62, 60};
      try {
          Synthesizer synthesizer = MidiSystem.getSynthesizer();
          synthesizer.open();
          MidiChannel channel = synthesizer.getChannels()[0];
 
          for (int note : notes) {
              channel.noteOn(note, 50);
              try {
                  Thread.sleep(200);
              } catch (InterruptedException e) {
                  break;
              } finally {
                  channel.noteOff(note);
              }
          }
      } catch (MidiUnavailableException e) {
          e.printStackTrace();
      }
  }
}


See example of Java MIDI application:
XenoHarmonica

7 comments:

Anonymous said...

I ran it with Eclipse and got no sound.

Anonymous said...

Works perfectly through Eclipse..

Anonymous said...

I got nothing on eclipse

Anonymous said...

You need to make sure that eclipse is using a JDK and not a JRE. Window > Preferences > Java > Installed JREs. You can add a JDK by pointing to the JDK install directory usually C:\Program Files\Java\jdk 1.6.x. Select this as your default JRE. I just remove the JREs listed in eclipse to make sure that I'm running from the JDK and not a JRE.

fridemar said...

import javax.sound.midi.*;

public class MidiSynthesizerSample {
static void main(args) {
def notes = [60, 62, 64, 65, 67, 69, 71, 72, 72, 71, 69, 67, 65, 64, 62, 60]
def synth = MidiSystem.getSynthesizer()
def vel = 50 // velocity from 0..127
def dur = 100 // duration in milliseconds

synth.open()
def channel = synth.getChannels()[0]

notes.each{
channel.noteOn(it, vel)
Thread.sleep(dur)
channel.noteOff(it)
}
}
}

/* Thank you dear poster of the introductory code snippet for producing midi tones. In response to it, I simplified the snippet in Groovy script and left a link-enriched version as a
GoogleSideWiki comment (http://www.google.com/sidewiki/entry/fridemar/id/UlUuTceUtyhYnCdlF_ZuR6RvpAU) on this page.
Unfortunately Google's SiteWiki doesn't preserve whitespace indentation. How do you indent your code samples here? ("pre" tags were not accepted) -- fridemar */

fridemar said...

Dear Xantorohara,
for convenience, I left a format preserving copy on my blog here:

fridemar.blogspot:SimpleGroovyMidiSynthesizer

Frog007 said...

Seems that there is some problem with hosting, unable to run applet and download dist