MIDI beginner - need to play one note

我怕爱的太早我们不能终老 提交于 2019-11-30 12:52:51
user2955146

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 ) { }
        mChannels[0].noteOff(60);//turn of the note


      } catch (MidiUnavailableException e) {}
   }

}    

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.

Alpesh Gediya
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!