写在前面
上一篇博客的内容我们介绍了一个最简单的音乐播放器的基本结构和实现代码,那么本篇内容我们只做一些稍微的变通,也要把MidiEvent的相关参数设置说明清楚。以下阅读最好结合本博客系列上一篇文章。
1.生成MidiEvent的四个步骤
(1)制造一个Message:
ShortMessage a = new ShortMessage();
(2)将控制命令放入Message中:
a.setMessage(144, 1, 44, 100);
(3)用这一Message生成一个新的MidiEvent:
MidiEvent noteOn = new MidiEvent(a, 1);
(4)将此MidiEvent放入Track中:
track.add(noteOn);
2.MIDI Message : MidiEvent的核心
(1)setMessage的参数设置:
a.setMessage(144, // Message type:144 means NOTE ON while 128 means NOTE OFF
1, // Channel:as a musician in a band,channel 1 represents musician1 while 8 represents musician8
44, // Note to play:A number from 0 to 127,going from low to high notes
100); // Velocity:How fast and hard the key is pressed.0 is too soft to hear anything, 100 is a good default
(2)改变信息的几种情形:
改变音调note(* *括住的表示改变部分):
a.setMessage(144, 1, *20*, 100);
改变音调持续时间(* *括住的表示改变部分):
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, *3*);
改变乐器(* *括住的表示改变部分):
first.setMessage(*192*, 1, *102*, 0)
3.用命令行输入控制声音信号(代码)
import javax.sound.midi.*; // The midi package is necessary
public class MiniMusicCmdLine {
public static void main(String[] args) {
MiniMusicCmdLine mini = new MiniMusicCmdLine();
if (args.length < 2) {
System.out.println("Don't forget the instrum and note args");
} else {
int instrument = Integer.parseInt(args[0]);
int note = Integer.parseInt(args[1]);
mini.play(instrument, note);
}
}
public void play(int instrument, int note) {
try {
// Get a sequencer and open it
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4); //Treat the arguments as Ready-bake arguments
Track track = seq.createTrack(); // Ask the sequence for a track
MidiEvent event = null;
// Put some MidiEvents into the Track, the setMessage() method is what we should really care
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, 16);
track.add(noteOff);
player.setSequence(seq); // Give the sequence to the Sequencer
// like pushing a CD to a CD player
player.start(); // Start the sequencer like pushing PLAY
}
catch(Exception ex) {
ex.printStackTrace();
}
} // Close play
} // Close class
注意的是运行时必须输入instrument和note的值,方式为:
java MiniMusicCmdLine 100 30
(整数可以自行设置)
方可听到声音。