问题
I have this code to play music (found online):
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MusicBackground {
public static void main(String[] args) throws Exception {
URL url = MusicBackground.class.getResource("backgroundMusic.wav");
AudioClip clip = Applet.newAudioClip(url);
clip.play();
Thread.sleep(1000);
clip.loop();
}
}
It works fine alone. But the thing is that after I implemented it into my game, it either plays the music when I'm launching the music class, or when I run the entire game, it runs the game without the music. Here is my Boot class for my game:
import static helpers.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import helpers.Clock;
import helpers.StateManager;
public class Boot {
public Boot() {
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
//Main game loop
while (!Display.isCloseRequested()) {
Clock.update();
StateManager.update();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void main(String[] args) {
new Boot();
}
}
I know that the music background class is in public static void main. But how do I implement it into the boot class ?
回答1:
Change your background music class to implement runnable:
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
import java.lang.Runnable;
public class MusicBackground implements Runnable {
public void run() throws Exception {
URL url = MusicBackground.class.getResource("backgroundMusic.wav");
AudioClip clip = Applet.newAudioClip(url);
clip.play();
Thread.sleep(1000);
clip.loop();
}
}
Then you can spawn a thread for the background music in your game's main thread. If you just direct call or paste that background music code in the main game loop, then the .sleep call will cause the entire program to sleep (as it is currently one thread). So, this is what your main method will look like now:
import static helpers.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import helpers.Clock;
import helpers.StateManager;
public class Boot {
public Boot() {
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
Thread backgroundPlayer;
Try {
backgroundPlayer = new Thread(new MusicBackground());
backgroundPlayer.start();
}
catch(Exception e)
{
System.out.println("Problem firing the background thread");
e.printStackTrace();
}
//Main game loop
while (!Display.isCloseRequested()) {
Clock.update();
StateManager.update();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void main(String[] args) {
new Boot();
}
}
来源:https://stackoverflow.com/questions/55424082/trouble-launching-game-and-music-at-the-same-time-when-pressing-run-on-eclip