16

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2366366
  • 161
  • 1
  • 1
  • 3

2 Answers2

25

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.

Stephan
  • 41,764
  • 65
  • 238
  • 329
user2955146
  • 351
  • 3
  • 5
3

Here you go :

MIDI Tag Info on stackoverflow

  1. UnderStanding MIDI
  2. Tutorial on Oracle
  3. Accessing MIDI
  4. MIdi Synthesis
Blunderchips
  • 534
  • 4
  • 22
Alpesh Gediya
  • 3,706
  • 1
  • 25
  • 38
  • I also want to add another link that was very helpful for me: https://www.cs.cmu.edu/~music/cmsip/readings/MIDI%20tutorial%20for%20programmers.html – Yolomep Aug 29 '20 at 22:54