Professor provided us with some video game code and we had to alter/add to it. Been trying to add audio for background music, player colliding with enemy, player dying, colliding with treasure, and firing a gun. I have all the sound files but its been tough trying to integrate them. Im not so sure where to put them or if my code is correct, but this is what I have so far.
I can't get any sound effects or background music to play when I run the game.
private MediaPlayer backgroundMusicPlayer;
private String playerCollideEnemyMusicFile = "player_collide_enemy.wav";
private String playerDyingMusicFile = "player_die.wav";
private String playerCollideTreasureMusicFile = "treasure.wav";
private String playerFiringMusicFile = "player_firing.wav";
private void playSound(String musicFile) {
String musicFileUrl = this.getClass().getResource("/resources/" + musicFile).toExternalForm();
AudioClip audioClip = new AudioClip(musicFileUrl);
audioClip.play();
}
private void playEnemySound() {
playSound(playerCollideEnemyMusicFile);
}
private void playDyingSound() {
playSound(playerDyingMusicFile);
}
private void playTreasureSound() {
playSound(playerCollideTreasureMusicFile);
}
} else if (r.getFill().equals(Color.GREEN)) { // GREEN = treasure/chest
Treasure t = getTreasure(r);
if (!t.isOpen()) {
score.set(score.get() + 10); // increase the score
chestCount--; // decrease our global chest count to track end of level
t.openNow(); // open the chest so it can't be opened twice
}
playTreasureSound();
When I run my code, the game runs, but as soon as I do something that's supposed to have a sound effect(collide with enemy, pick up treasure), the game freezes and I get these error messages spamming down my console:
at main.Game.playSound(Game.java:102)
at main.Game.playTreasureSound(Game.java:115)
at main.Game.collisionCheck(Game.java:218)
at main.Game.access$1(Game.java:200)
at main.Game$1.handle(Game.java:240)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.lambda$handle$484(AnimationTimer.java:57)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.handle(AnimationTimer.java:56)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:357)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:506)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$404(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)