我在互联网上查看了播放 wav 文件的方法,但我发现它们不会在单独的线程上播放,因此会导致程序停止,直到歌曲完成,这不适用于游戏。但是,当我尝试在单独的线程上播放所有内容时,它会滞后。有没有人可以解决这个问题?
注意:我也在不断地在背景上绘画:
public class DrawThread extends Thread {
JFrame j;
public DrawThread(JFrame frame) {
j = frame;
}
public void run() {
while (!(isInterrupted())) {
if (j.isDisplayable() && j.isActive() && j.isEnabled())
j.update(j.getGraphics());
}
}
}
并且更新只是调用paint,即:
public void paint(Graphics g) {
Graphics2D bg = (Graphics2D) g;
bg.setBackground(Color.black);
int w = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int h = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
if (time < 500) {
x[time] = r.nextInt(w) + 150;
y[time] = h;
z[time] = r.nextInt(w) + 150;
time++;
}
for (int i = 0; i < time; i++) {
y[i] -= forward;
x[i] -= right;
if (y[i] < 1) {
x[i] = r.nextInt(400) - 200;
y[i] = 300;
z[i] = r.nextInt(400) - 200;
} else if (y[i] > 300) {
x[i] = r.nextInt(400) - 200;
y[i] = 1;
z[i] = r.nextInt(400) - 200;
}
if (x[i] > 200)
x[i] = -200;
else if (x[i] < -200)
x[i] = 200;
bg.setColor(color);
bg.drawLine(
getWidth() / 2 + (int) Math.round(x[i] * 200 / y[i]),
getHeight() / 2 + (int) Math.round(z[i] * 200 / y[i]),
getWidth()
/ 2
+ (int) Math.round((x[i] + right) * 200
/ Math.abs(y[i] + forward)),
getHeight()
/ 2
+ (int) Math.round((z[i]) * 200
/ Math.abs(y[i] + forward)));
}
}
编辑:添加我正在使用的音乐播放器类(我已切换到 BigClip):
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import org.crystalix.util.SoundListener;
public class MSHandler {
public static boolean pause = false;
public static boolean stop = false;
private static HashMap<String, BigClip> clips = new HashMap<String, BigClip>();
public static void stopAll() {
Collection<BigClip> c = clips.values();
for (BigClip b : c) {
System.out.println("Stopping "+b.toString());
b.stop();
System.out.println("Stopped "+b.toString());
}
}
public static void playMusic(File file) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
BigClip clip = new BigClip();
clip.open(audioIn);
clip.addLineListener(new SoundListener());
clip.loop(1);
clip.start();
clips.put(file.getName(), clip);
} catch (Exception e) {
System.err.println("Sound could not be started!");
e.printStackTrace(System.err);
}
}
}