如何使用Java在Midi文件中列出乐器名称?

时间:2019-04-13 04:04:57

标签: java instruments midi

我使用以下代码播放midi文件,但找不到使用的乐器列表:

      try
      {
        Sequence sequence=MidiSystem.getSequence(file);                                  // From file

        int trackNumber=0;
        for (Track track : sequence.getTracks())
        {
          trackNumber++;
          System.out.println("Track "+trackNumber+": size = "+track.size());
          System.out.println();
          for (int i=0;i<track.size();i++)
          {
            MidiEvent event=track.get(i);
            System.out.print("@"+event.getTick()+" ");
            if (message instanceof ShortMessage)
            {
              ShortMessage sm=(ShortMessage)message;
              System.out.print("Channel: "+sm.getChannel()+" "+new String(sm.getMessage())+" | ");
            }
            else Out("Other message: "+message.getClass());
          }
          System.out.println();
        }

        Sequencer sequencer=MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(sequence);
        sequencer.start();                                                                               
      }
      catch (Exception e) { e.printStackTrace(); }

我做了一些搜索,有类似的问题,但是没有一个有直接的答案,我只想列出文件中使用的乐器,例如钢琴,鼓……我知道信息隐藏在消息中[也许叫做“程序”? ],但我找不到它。

1 个答案:

答案 0 :(得分:0)

这是答案,我终于弄清楚了:

Instrument instruments[];
Soundbank sb=synthesizer.getDefaultSoundbank();
if (sb!=null) instruments=synthesizer.getDefaultSoundbank().getInstruments();

...

      try
      {
        Sequence sequence=MidiSystem.getSequence(file);                                  // From file

        int trackNumber=0;
        for (Track track : sequence.getTracks())
        {
          System.out.print("Track "+(trackNumber++)+" : ");
          MidiEvent event=track.get(0);
          MidiMessage message=event.getMessage();
          if (message instanceof ShortMessage)
          {
            ShortMessage sm=(ShortMessage)message;
            if (sm.getCommand()==192) Out("sm.getChannel()="+sm.getChannel()+"  sm.getData1()="+sm.getData1()+"  "+instruments[sm.getData1()]);
          }
        }

输出看起来像这样:

Track 0 : sm.getChannel()=0  sm.getData1()=0  Instrument: Piano 1      bank #0 preset #0
Track 1 : sm.getChannel()=1  sm.getData1()=16  Instrument: Organ 1      bank #0 preset #16
Track 2 : sm.getChannel()=2  sm.getData1()=56  Instrument: Trumpet      bank #0 preset #56
Track 3 : sm.getChannel()=3  sm.getData1()=25  Instrument: Steel-str.Gt bank #0 preset #25