2015/6/15
相对完整的音符播放程序:
package Music;
import javax.sound.midi.*;
public class MiniMusicCmdLine {//这是第一个
public static void main(String[] args){
MiniMusicCmdLine mini=new MiniMusicCmdLine();
if(args.length<2){//检测接收到的用户信息是否完整
System.out.println("Don't forget the instrument and note args");
}else{
int instrument=Integer.parseInt(args[0]);//获取第一号信息作为乐器instrument(仪器)
int note=Integer.parseInt(args[1]);//为音符
mini.play(instrument,note);//调用play(……)方法
// mini.play(70,44);
}
}
public void play(int instrument,int note){
try{
//用MidiSystem.getSequencer创建音序器
Sequencer player=MidiSystem.getSequencer();
//将音序器打开
player.open();
//创建相应的序列对象
Sequence seq=new Sequence(Sequence.PPQ,4);
//用seq.createTrack()创建音轨对象
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,8);
track.add(noteOff);
//将音符序列天骄到音序器中
player.setSequence(seq);
//通过音序器开始播放音乐
player.start();
}catch(Exception e){
e.printStackTrace();
}
}
}