第11章 程序料理----miniMusic(2)

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();
		}
	}

}




  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值