我正在编写一个包含动画的Java Applet,该动画会触发要播放的MIDI声音。声音由以下类播放 - 它启动自己的Thread - 无论如何,Applet中的动画在声音播放时暂停。我没有看到我在这里做错了什么,我希望动画不会因新分配的线程暂停...
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Synthesizer;
public class ChromaticSynth implements Runnable{
//vars
private Synthesizer synth;
private MidiChannel mchannel;
private int playNote;
private Thread myThread;
//constructor
public ChromaticSynth(int playNote){
try {
synth=MidiSystem.getSynthesizer();
synth.open();
mchannel=synth.getChannels()[0];
this.playNote=playNote;
myThread=new Thread(this);
myThread.start();
} catch (MidiUnavailableException ex) {
Logger.getLogger(ChromaticSynth.class.getName()).log(Level.SEVERE, null, ex);
}
}
//play sound
public void run(){
mchannel.noteOn(playNote,50);
}
}
ChromaticSynth类以下列方式使用(将代码缩减为相关部分):
import chromatic.ChromaticSynth;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class ChromaticPanel extends JPanel{
//vars
...
//constructor
public ChromaticPanel(){
super();
...
}
//paint
protected void paintComponent(Graphics g){
super.paintComponent(g);
//draw something
g.setColor(Color.white);
g.draw(...);
if(noteshouldbeplayed)
ChromaticSynth cs=new ChromaticSynth(playNote);
}
}
Panel的repaint() - 方法由包含ChromaticPanel的JFrame中的javax.swing.Timer重复调用以绘制动画。
谢谢你的帮助!