MIDI beginner - need to play one note

user2366366 picture user2366366 · May 9, 2013 · Viewed 9.8k times · Source

I don't know very much about Java's MIDI function. In fact, it utterly bewilders me. what I'd like to do however is just build a simple application that will play one note.

How to play a single MIDI note using Java Sound?

The support for this out on the web is almost nonexistent, and I am totally at a loss.

Answer

user2955146 picture user2955146 · Apr 7, 2016

I know this is a really old question, but, as a novice programmer, I had a very difficult time figuring out how to do this, so I thought I would share the following hello-world-style program that gets Java to play a single midi note in order to help anyone else getting started.

import javax.sound.midi.*;

public class MidiTest{

    public static void main(String[] args) { 
      try{
        /* Create a new Sythesizer and open it. Most of 
         * the methods you will want to use to expand on this 
         * example can be found in the Java documentation here: 
         * https://docs.oracle.com/javase/7/docs/api/javax/sound/midi/Synthesizer.html
         */
        Synthesizer midiSynth = MidiSystem.getSynthesizer(); 
        midiSynth.open();
    
        //get and load default instrument and channel lists
        Instrument[] instr = midiSynth.getDefaultSoundbank().getInstruments();
        MidiChannel[] mChannels = midiSynth.getChannels();
        
        midiSynth.loadInstrument(instr[0]);//load an instrument
    
    
        mChannels[0].noteOn(60, 100);//On channel 0, play note number 60 with velocity 100 
        try { Thread.sleep(1000); // wait time in milliseconds to control duration
        } catch( InterruptedException e ) {
            e.printStackTrace();
        }
        mChannels[0].noteOff(60);//turn of the note
    
    
      } catch (MidiUnavailableException e) {
         e.printStackTrace();
      }
   }

}    

The above code was primarily created by cutting, pasting, and messing around with code found in several online tutorials. Here are the most helpful tutorials that I found:

http://www.ibm.com/developerworks/library/it/it-0801art38/

This is a great tutorial and probably has everything you are looking for; however, it may be a little overwhelming at first.

http://patater.com/gbaguy/javamidi.htm

Features nonworking code written by a 15 year old. This was - surprisingly - the most helpful thing I found.