我在java中编写了一个播放声音的方法。它在我的ubuntu笔记本电脑上工作正常但在Windows上无法正常工作。没有错误,但我认为它可能因为某种原因绕过了Windows上的排水方法。
public static void runOnce(final String location) {
new Thread(new Runnable() {
public void run() {
try {
File audioFile = new File(Game.gameFolder + "/sounds/" + location);
final AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
final Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.open(audioStream);
audioClip.start();
audioClip.drain();
try {
audioClip.close();
audioStream.close();
} catch (Exception e) {
System.out.println("heyeyeyeyye");
}
System.out.println("sound method ran");
} catch(Exception e) {}
}
}).start();
}
谢谢 - 泰勒
编辑: 我记得实际上它在使用排水管之前在窗户上工作但经过一段时间之后它不会再加载所以我转换到排水管
答案 0 :(得分:0)
我建议您使用try-with-resources
,并join()
启动线程,永远不会吞掉Exception
中的消息。像,
public static void runOnce(final String location) {
File audioFile = new File(Game.gameFolder + "/sounds/" + location);
Thread t = new Thread(new Runnable() {
public void run() {
try (AudioInputStream audioStream = AudioSystem
.getAudioInputStream(audioFile);) {
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
try (Clip audioClip = (Clip) AudioSystem.getLine(info);) {
audioClip.open(audioStream);
audioClip.start();
audioClip.drain();
}
System.out.println("heyeyeyeyye");
System.out.println("sound method ran");
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
t.join();
}