我正在尝试制作一款游戏,而我目前正试图为其添加声音,但由于缺乏经验,我没有这样做,所以我要求你提供帮助。 如何在游戏中添加背景歌曲?
答案 0 :(得分:1)
启动一个单独的线程来播放声音。在这个帖子中播放它。通过这种方式,您的游戏将会运行,同时您可以运行声音。
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
答案 1 :(得分:0)
public static void music() {
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try {
BGM = new AudioStream(new FileInputStream("som.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
} catch(IOException error) {
System.out.println("Error!!!");
}
MGP.start(loop);
}