gpt4 book ai didi

java - 如何在Java中的新线程中播放.MIDI文件?

转载 作者:行者123 更新时间:2023-11-30 05:02:59 25 4
gpt4 key购买 nike

我正在用 Java 重新制作游戏的一部分,我需要知道如何播放 MIDI 声音文件。最好不涉及导入任何外部库。它还必须可以在新线程中运行,以便我可以将各个声音叠加在背景歌曲上。

感谢您的想法和时间。

最佳答案

此代码同时播放两个 MIDI 轨道(第一个对话框一消失,第二个序列就会开始)。没有显式创建线程,但我想如果将它们包装在 Thread 对象中,它的工作原理大致相同。

import java.net.URL;
import java.util.Locale;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Transmitter;
import javax.swing.JOptionPane;
import org.apache.commons.lang.StringUtils;

class PlayMidi {

public static boolean useExternalSynth = false;

public static void main(String[] args) throws Exception {
MidiDevice receivingDevice = getReceivingDevice();
receivingDevice.open();

URL url1 = new URL("http://pscode.org/media/EverLove.mid");

Sequence sequence1 = MidiSystem.getSequence(url1);
Sequencer sequencer1 = MidiSystem.getSequencer(false);
Transmitter tx1 = sequencer1.getTransmitter();
Receiver rx1 = receivingDevice.getReceiver();
tx1.setReceiver(rx1);

sequencer1.open();
sequencer1.setSequence(sequence1);

URL url2 = new URL("http://pscode.org/media/AftrMdnt.mid");

Sequence sequence2 = MidiSystem.getSequence(url2);
Sequencer sequencer2 = MidiSystem.getSequencer(false);
Transmitter tx2 = sequencer2.getTransmitter();
Receiver rx2 = receivingDevice.getReceiver();
tx2.setReceiver(rx2);

sequencer2.open();
sequencer2.setSequence(sequence2);

sequencer1.start();
JOptionPane.showMessageDialog(null, "Everlasting Love");
sequencer2.start();
JOptionPane.showMessageDialog(null, "After Midnight");
}

private static MidiDevice getReceivingDevice()
throws MidiUnavailableException {
for (MidiDevice.Info mdi: MidiSystem.getMidiDeviceInfo()) {
MidiDevice dev = MidiSystem.getMidiDevice(mdi);
if (dev.getMaxReceivers() != 0) {
String lcName =
StringUtils.defaultString(mdi.getName())
.toLowerCase(Locale.ENGLISH);
if (lcName.contains(useExternalSynth? "usb": "java")) {
return dev;
}
}
}
return null;
}

}

关于java - 如何在Java中的新线程中播放.MIDI文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6038917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com