在 Java 中播放时将 midi 文件输出到控制台
Posted
技术标签:
【中文标题】在 Java 中播放时将 midi 文件输出到控制台【英文标题】:Output midi file to console while being played in Java 【发布时间】:2019-02-16 12:24:11 【问题描述】:我正在尝试读取 MIDI 文件并在播放音符、音符和力度时输出。 This 会很好用,但在播放音符时它不会实时输出数据。播放midi的代码:
package midistep;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequencer;
public class MidiReadAndPlay
public static void main(String[] args) throws Exception
Sequencer sequencer;
sequencer = MidiSystem.getSequencer();
sequencer.open();
InputStream is = new BufferedInputStream(new FileInputStream(new File("midifile.mid")));
sequencer.setSequence(is);
sequencer.start();
我之前提到的问题中的代码不会实时输出数据。它只是一次输出所有内容。我希望它在播放音符时输出音序器数据,以便以后使用。
【问题讨论】:
恐怕你需要创建两个线程,或者重写Sequencer
的逻辑。
我想应该可以将您自己的Receiver
连接到音序器的Transmitter
。
@CL。我怎么能做到这一点?你有一些代码的链接吗?
【参考方案1】:
及时输出notenote数据的解决方案是添加自定义code的receiver:
public class MidiReadAndPlay
public static Receiver synthRcvr = new CustomReceiver();
public static Transmitter seqTrans;
public static Synthesizer synth;
public static Sequencer sequencer;
public static Sequence sequence;
public static void main(String[] args) throws Exception
sequencer = MidiSystem.getSequencer();
sequence = MidiSystem.getSequence(new File("midi.mid"));
Sequencer sequencer = MidiSystem.getSequencer();
seqTrans = sequencer.getTransmitter();
seqTrans.setReceiver(synthRcvr);
sequencer.open();
sequencer.setSequence(sequence);
sequencer.start();
接收者:
public class CustomReceiver implements Receiver
public CustomReceiver()
public static final int NOTE_ON = 0x90;
public static final int NOTE_OFF = 0x80;
public static final String[] NOTE_NAMES = "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B";
@Override
public void send(MidiMessage message, long timeStamp)
if (message instanceof ShortMessage)
ShortMessage sm = (ShortMessage) message;
System.out.print("Channel: " + sm.getChannel() + " ");
if (sm.getCommand() == NOTE_ON)
int key = sm.getData1();
int octave = (key / 12)-1;
int note = key % 12;
String noteName = NOTE_NAMES[note];
int velocity = sm.getData2();
System.out.println("Note on, " + noteName + octave + " key=" + key + " velocity: " + velocity);
else if (sm.getCommand() == NOTE_OFF)
int key = sm.getData1();
int octave = (key / 12)-1;
int note = key % 12;
String noteName = NOTE_NAMES[note];
int velocity = sm.getData2();
System.out.println("Note off, " + noteName + octave + " key=" + key + " velocity: " + velocity);
else
System.out.println("Command:" + sm.getCommand());
else
System.out.println("Other message: " + message.getClass());
@Override
public void close()
【讨论】:
以上是关于在 Java 中播放时将 midi 文件输出到控制台的主要内容,如果未能解决你的问题,请参考以下文章