1 import javax.sound.midi.*; 2 3 public class Midi { 4 public void play(int instrument, int note) { 5 try { 6 Sequencer player = MidiSystem.getSequencer(); 7 player.open(); 8 9 Sequence seq = new Sequence(Sequence.PPQ, 4);//divisionType, resolution 10 11 Track track = seq.createTrack(); 12 13 ShortMessage first = new ShortMessage(); 14 first.setMessage(192, 1, instrument, 0); 15 MidiEvent change = new MidiEvent(first, 1); 16 track.add(change); 17 18 ShortMessage a = new ShortMessage(); 19 a.setMessage(144, 1, note, 100);//command channel data1 data2 20 //144 -note on 128 -note off 21 //1 - 频道 22 //44 - 音符 0-127 23 //100 - 音道 24 MidiEvent noteOn = new MidiEvent(a, 1); //tick - the time-stamp for the event, in MIDI ticks 25 track.add(noteOn); 26 27 ShortMessage b = new ShortMessage(); 28 b.setMessage(128, 1, note, 100);//command channel data1 data2 29 MidiEvent noteOff = new MidiEvent(b, 16); //tick - the time-stamp for the event, in MIDI ticks 30 track.add(noteOff); 31 32 player.setSequence(seq); 33 player.start(); 34 //while( player.isRunning() ) { 35 // try { 36 // Thread.sleep(1000); 37 // } catch (Exception e) {} 38 //} 39 //player.close(); 40 41 } catch( Exception ex) { 42 ex.printStackTrace(); 43 } 44 } 45 46 public static void main(String[] args) { 47 if (args.length < 2) { 48 System.out.println("Don‘t forget the instrument and note args"); 49 } 50 else { 51 int instrument = Integer.parseInt(args[0]); 52 int note = Integer.parseInt(args[1]); 53 Midi midi = new Midi(); 54 midi.play(instrument, note); 55 } 56 } 57 }
时间: 2024-10-19 19:01:04