0

我正在编写一个 Java Applet,其中包含一个触发播放 MIDI 声音的动画。声音由以下类播放 - 它启动自己的线程 - 无论如何,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);                    

    }


}

面板的 repaint() 方法由包含 ChromaticPanel 的 JFrame 中的 javax.swing.Timer 重复调用以绘制动画。

谢谢你的帮助!

4

0 回答 0