import javax.sound.midi.*; import javax.swing.*; public class miniplayer1{ Panel panel; JFrame frame; public MidiEvent MakeEvent(int comd,int chan,int note,int vol,int tick){ MidiEvent event; event = null; try{ ShortMessage a = new ShortMessage(); a.setMessage(comd, chan, note, vol); event = new MidiEvent(a,tick); }catch(Exception ex){} return event; } public void setGui(){ frame = new JFrame("My music App"); panel = new Panel(); frame.getContentPane().add(panel); frame.setBounds(100, 100, 200, 200); frame.setVisible(true); } public void go(){ setGui(); try{ Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); int [] eventIwant = {127}; sequencer.addControllerEventListener(panel,eventIwant); Sequence seq = new Sequence(Sequence.PPQ,4); Track track = seq.createTrack(); for(int i = 5; i < 200; i += 4){ int r = (int)(Math.random() * 50) + 1; track.add(MakeEvent(144,1,r,100,i)); track.add(MakeEvent(176,1,127,0,i)); track.add(MakeEvent(128, 1, r,100, i+3)); } sequencer.setSequence(seq); sequencer.setTempoInBPM(220); sequencer.start(); } catch(Exception ex){} } public void controlChange(ShortMessage event){ System.out.println("la "); } }
import javax.swing.*; import javax.sound.midi.*; import java.awt.*; public class Panel extends JPanel implements ControllerEventListener{ boolean msg = false; public void controlChange(ShortMessage a){ msg = true; repaint(); } public void paintComponent(Graphics g){ if(msg){ int red = (int)(Math.random() * 127); int gre = (int)(Math.random() * 127); int blue = (int)(Math.random() * 127); Color color = new Color(red,gre,blue); g.setColor(color); int x = (int)(Math.random() * 40) + 10; int y = (int)(Math.random() * 40) + 10; int ht = (int)(Math.random() * 120) + 10; int wid = (int)(Math.random() * 120) + 10; g.fillRect(x, y, wid, ht); msg = false; } } }
public class Test { public static void main(String[] args) { miniplayer1 play = new miniplayer1(); play.go(); } }
Sequencer(相当于CD播放器)是按照tick(拍)依次检查,1到2到3...
建立一个Sequence的对象seq,给seq的track依次加入MidiEvent
在miniplayer1类中for循环解释为:
向track中加入某个音调的noteOn事件和noteOff事件
中间行向track中加入127类型事件,并且设置在noteOn的同一拍执行
sequencer.addControllerEventListener(panel,eventIwant)表示:
panel想要127事件,当事件源sequencer向panel传递信息,让其repaint
msg的存在是为了让第一次frame被setVisible时不作图
原文:http://www.cnblogs.com/gabygoole/p/4916044.html