代码之家  ›  专栏  ›  技术社区  ›  Frank

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

  •  0
  • Frank  · 技术社区  · 5 年前

    我使用以下代码播放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(); }
    

    0 回复  |  直到 5 年前
        1
  •  0
  •   Frank    5 年前

    答案是这样的,我终于想出来了:

    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