美文网首页
史上第一个声音播放程序第二版

史上第一个声音播放程序第二版

作者: 狂舞曲少WA几个好不 | 来源:发表于2016-11-27 20:29 被阅读0次

    使用命令行参数

    package book.java;
    
    import java.nio.channels.ShutdownChannelGroupException;
    
    import javax.sound.midi.MidiEvent;
    import javax.sound.midi.MidiSystem;
    import javax.sound.midi.Sequence;
    import javax.sound.midi.Sequencer;
    import javax.sound.midi.ShortMessage;
    import javax.sound.midi.Track;
    
    public class MideSound {
    
        public MideSound() {
            // TODO Auto-generated constructor stub
        }
    
        public void play(int instrument, int note) {
            //获得播放器并打开
            try {
            Sequencer player = MidiSystem.getSequencer();
            player.open();
            
            Sequence seq = new Sequence(Sequence.SMPTE_30DROP, 4);
            
            Track track = seq.createTrack();
    
            ShortMessage cMessage = new ShortMessage();
            cMessage.setMessage(192, 1, instrument, 0);
            MidiEvent first = new MidiEvent(cMessage, 1);
            track.add(first);
            
            ShortMessage aMessage = new ShortMessage();
            aMessage.setMessage(144, 1, note, 100);
            MidiEvent noteOn = new MidiEvent(aMessage, 1);
            track.add(noteOn);
            
            ShortMessage bMessage = new ShortMessage();
            bMessage.setMessage(144, 1, note, 100);
            MidiEvent noteOff = new MidiEvent(bMessage, 16);
            track.add(noteOff);
            
            player.setSequence(seq);
            player.start();
            } catch(Exception ex) {
                ex.printStackTrace();
            } 
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 构建播放器对象
            MideSound mini = new MideSound();
            if (args.length < 2) {
                System.out.println("Don't forget the instrument and note args!");
            } else {
                int instrument = Integer.parseInt(args[0]);
                int note = Integer.parseInt(args[1]);
                mini.play(instrument, note);
            }
            mini.play();
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:史上第一个声音播放程序第二版

          本文链接:https://www.haomeiwen.com/subject/avynpttx.html