Skip to content

Commit

Permalink
fix: 添加音频控制
Browse files Browse the repository at this point in the history
  • Loading branch information
TwoKe committed Feb 3, 2024
1 parent a94ee60 commit aa81ad1
Show file tree
Hide file tree
Showing 24 changed files with 240 additions and 8 deletions.
163 changes: 163 additions & 0 deletions src/main/java/cn/com/twoke/game/audio/AudioPlayer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package cn.com.twoke.game.audio;

import cn.com.twoke.game.main.Game;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Random;

public class AudioPlayer {

public static int MENU_1 = 0;
public static int LEVEL_1 = 1;
public static int LEVEL_2 = 2;

public static int DIE = 0;
public static int JUMP = 1;
public static int GAMEOVER = 2;
public static int LVL_COMPLETED = 3;
public static int ATTACK_ONE = 4;
public static int ATTACK_TWO = 5;
public static int ATTACK_THREE = 6;

private Clip[] songs, effects;
private int currentSongId;
private float volume = 0.5f;
private boolean songMute, effectMute;
private Random rand = new Random();

public AudioPlayer() {
loadSongs();
loadEffects();
playSong(MENU_1);
}


private void loadSongs() {
String[] names = {"menu", "level1", "level2"};
songs = new Clip[names.length];
for (int i = 0; i < songs.length; i++) {
songs[i] = getClip(names[i]);
}

}


private void loadEffects() {
String[] names = {"die", "jump", "gameover", "lvlcompleted", "attack1", "attack2", "attack3"};
effects = new Clip[names.length];
for (int i = 0; i < effects.length; i++) {
effects[i] = getClip(names[i]);
}
updateEffectsVolume();
}


private Clip getClip(String name) {
URL url = getClass().getResource("/audio/"+name+".wav");
AudioInputStream audio = null;
Clip c = null;
try {
audio = AudioSystem.getAudioInputStream(url);
c = AudioSystem.getClip();
c.open(audio);
return c;
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}

return null;
}


private void updateSongVolume() {
FloatControl gainControl = (FloatControl) songs[currentSongId].getControl(FloatControl.Type.MASTER_GAIN);
float range = gainControl.getMaximum() - gainControl.getMinimum();
float gain = (range * volume) + gainControl.getMinimum();
gainControl.setValue(gain);
}

private void updateEffectsVolume() {
for (Clip effect : effects) {
FloatControl gainControl = (FloatControl) effect.getControl(FloatControl.Type.MASTER_GAIN);
float range = gainControl.getMaximum() - gainControl.getMinimum();
float gain = (range * volume) + gainControl.getMinimum();
gainControl.setValue(gain);
}
}

public void toggleSongMute() {
this.songMute = !songMute;
for (Clip song : songs) {
BooleanControl booleanControl = (BooleanControl) song.getControl(BooleanControl.Type.MUTE);
booleanControl.setValue(songMute);
}
}

public void toggleEffectMute() {
effectMute = !effectMute;
for (Clip effect : effects) {
BooleanControl booleanControl = (BooleanControl) effect.getControl(BooleanControl.Type.MUTE);
booleanControl.setValue(effectMute);
}
if (!effectMute)
playEffect(JUMP);
}

public void playEffect(int effectId) {
effects[effectId].setMicrosecondPosition(0);
effects[effectId].start();
}

public void playAttackSound() {
int start = 4;
start += rand.nextInt(3);
playEffect(start);
}

public void setVolume(float volume) {
this.volume = volume;
if (this.volume < 0) {
this.volume = 0;
} else if (this.volume > 1) {
this.volume = 1;
}
updateSongVolume();
updateEffectsVolume();
}

public void stopSong() {
if (songs[currentSongId].isActive()) {
songs[currentSongId].stop();
}
}

public void setLevelSong(int lvlIndex) {
if (lvlIndex % 2 == 0) {
playSong(LEVEL_1);
} else {
playSong(LEVEL_2);
}
}

public void lvlCompleted() {
stopSong();
playEffect(LVL_COMPLETED);
}

public void playSong(int songId) {
stopSong();
currentSongId = songId;
updateSongVolume();
songs[currentSongId].setMicrosecondPosition(0);
songs[currentSongId].loop(Clip.LOOP_CONTINUOUSLY); // 循环播放
}

}
3 changes: 2 additions & 1 deletion src/main/java/cn/com/twoke/game/entities/EnemyManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ public void update(int[][] lvlData, Player player) {
isAnyActive = true;
}
}
if (!isAnyActive)
if (!isAnyActive) {
playing.setLevelCompleted(true);
}
}


Expand Down
5 changes: 5 additions & 0 deletions src/main/java/cn/com/twoke/game/entities/Player.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cn.com.twoke.game.entities;

import cn.com.twoke.game.audio.AudioPlayer;
import cn.com.twoke.game.gamestates.Playing;
import cn.com.twoke.game.main.Game;
import cn.com.twoke.game.utils.HelpMethods;
Expand Down Expand Up @@ -72,8 +73,11 @@ public void update() {
aniIndex = 0;
aniTick = 0;
playing.setPlayerDying(true);
playing.getGame().getAudioPlayer().playEffect(AudioPlayer.DIE);
} else if (aniIndex == GetSpriteAmount(DEAD) - 1 && aniTick >= ANI_SPEED - 1) {
playing.setGameOver(true);
playing.getGame().getAudioPlayer().stopSong();
playing.getGame().getAudioPlayer().playEffect(AudioPlayer.GAMEOVER);
} else {
updateAnimationTick();
}
Expand Down Expand Up @@ -258,6 +262,7 @@ private void updatePos() {
private void jump() {
if (inAir)
return;
playing.getGame().getAudioPlayer().playEffect(AudioPlayer.JUMP);
inAir = true;
airSpeed = jumpSpeed;
}
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/cn/com/twoke/game/gamestates/Menu.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void draw(Graphics g) {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
GameState.currentState = GameState.PLAYING;
setGameState(GameState.PLAYING);
}

@Override
Expand All @@ -74,6 +74,9 @@ public void mouseReleased(MouseEvent e) {
for (MenuButton button : buttons) {
if (isIn(e, button) && button.isMousePressed()) {
button.applyGameState();
if (button.getState() == GameState.PLAYING) {
game.getAudioPlayer().setLevelSong(game.getPlaying().getLevelManager().getLvlIndex());
}
break;
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/cn/com/twoke/game/gamestates/Playing.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public void loadNextLevel() {
resetAll();
levelManager.loadNextLevel();
player.setSpawn(levelManager.getCurrentLevel().getLvlSpawn());
getGame().getAudioPlayer().setLevelSong(levelManager.getLvlIndex());
}

public EnemyManager getEnemyManager() {
Expand Down Expand Up @@ -198,6 +199,7 @@ public void mouseClicked(MouseEvent e) {
if (!gameOver) {
if (e.getButton() == MouseEvent.BUTTON1) {
player.setAttack(true);
getGame().getAudioPlayer().playAttackSound();
}
}
}
Expand Down Expand Up @@ -307,6 +309,9 @@ public void setMaxLvlOffsetX(int maxLvlOffsetX) {

public void setLevelCompleted(boolean completed) {
this.completed = completed;
if (completed) {
getGame().getAudioPlayer().lvlCompleted();
}
}

public ObjectManager getObjectManager() {
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/cn/com/twoke/game/gamestates/State.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cn.com.twoke.game.gamestates;

import cn.com.twoke.game.audio.AudioPlayer;
import cn.com.twoke.game.main.Game;
import cn.com.twoke.game.ui.MenuButton;
import javafx.scene.input.MouseButton;
Expand All @@ -21,4 +22,15 @@ public boolean isIn(MouseEvent e, MenuButton mb) {
public Game getGame() {
return game;
}

public void setGameState(GameState gameState) {
switch (gameState) {
case MENU:
game.getAudioPlayer().playSong(AudioPlayer.MENU_1);
break;
case PLAYING: game.getAudioPlayer().setLevelSong(game.getPlaying().getLevelManager().getLvlIndex());
}
GameState.currentState = gameState;
}

}
7 changes: 6 additions & 1 deletion src/main/java/cn/com/twoke/game/levels/LevelManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,17 @@ public void loadNextLevel() {
if (lvlIndex >= levels.size()) {
lvlIndex = 0;
System.out.println("No More levels! Game Completed!");
GameState.currentState = GameState.MENU;
// GameState.currentState = GameState.MENU;
game.getPlaying().setGameState(GameState.MENU);
}
Level newLevel = levels.get(lvlIndex);
game.getPlaying().getEnemyManager().loadEnemies(newLevel);
game.getPlaying().getPlayer().loadLevelData(newLevel.getLevelData());
game.getPlaying().setMaxLvlOffsetX(newLevel.getMaxLvlOffsetX());
game.getPlaying().getObjectManager().loadObjects(newLevel);
}

public int getLvlIndex() {
return lvlIndex;
}
}
9 changes: 8 additions & 1 deletion src/main/java/cn/com/twoke/game/main/Game.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cn.com.twoke.game.main;

import cn.com.twoke.game.audio.AudioPlayer;
import cn.com.twoke.game.entities.Player;
import cn.com.twoke.game.gamestates.GameOptions;
import cn.com.twoke.game.gamestates.GameState;
Expand All @@ -24,6 +25,7 @@ public class Game implements Runnable
private Menu menu;
private AudioOptions audioOptions;
private GameOptions gameOptions;
private AudioPlayer audioPlayer;
public final static int TILES_DEFAULT_SIZE = 32;
public final static float SCALE = 2f;
public final static int TILES_IN_WIDTH = 26;
Expand All @@ -42,10 +44,15 @@ public Game() {
}

private void initClasses() {
this.audioOptions = new AudioOptions();
this.audioOptions = new AudioOptions(this);
this.menu = new Menu(this);
this.playing = new Playing(this);
this.gameOptions = new GameOptions(this);
this.audioPlayer = new AudioPlayer();
}

public AudioPlayer getAudioPlayer() {
return audioPlayer;
}

public AudioOptions getAudioOptions() {
Expand Down
13 changes: 12 additions & 1 deletion src/main/java/cn/com/twoke/game/ui/AudioOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
public class AudioOptions {
private VolumeButton volumeB;
private SoundButton musicButton,sfxButton;
public AudioOptions() {

private Game game;

public AudioOptions(Game game) {
this.game = game;
createSoundButton();
createVolumeButton();
}
Expand Down Expand Up @@ -62,9 +66,11 @@ else if (sfxButton.isIn(e)) {
public void mouseReleased(MouseEvent e) {
if (musicButton.isIn(e) && musicButton.isMousePressed()) {
musicButton.setMuted(!musicButton.isMuted());
game.getAudioPlayer().toggleSongMute();
}
else if (sfxButton.isIn(e) && sfxButton.isMousePressed()) {
sfxButton.setMuted(!sfxButton.isMuted());
game.getAudioPlayer().toggleEffectMute();
}
resetBools();
}
Expand Down Expand Up @@ -96,7 +102,12 @@ public void cleanMouseOver() {

public void mouseDragged(MouseEvent e) {
if (volumeB.isMousePressed()) {
float valueBefore = volumeB.getFloatValue();
volumeB.changeX(e.getX());
float valueAfter = volumeB.getFloatValue();
if (valueAfter != valueBefore) {
game.getAudioPlayer().setVolume(valueAfter);
}
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/cn/com/twoke/game/ui/GameOverOverlay.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,11 @@ public void mouseMoved(MouseEvent e) {
public void mouseReleased(MouseEvent e) {
if (replay.isIn(e) && replay.isMousePressed()) {
playing.resetAll();
playing.getGame().getAudioPlayer().setLevelSong(playing.getLevelManager().getLvlIndex());
}
else if (menu.isIn(e) && menu.isMousePressed()) {
playing.resetAll();
GameState.currentState = GameState.MENU;
playing.setGameState(GameState.MENU);
}

menu.resetBools();
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/cn/com/twoke/game/ui/LevelCompleteOverlay.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ public void mouseReleased(MouseEvent e) {
}
else if (menu.isIn(e) && menu.isMousePressed()) {
playing.resetAll();
GameState.currentState = GameState.MENU;
// GameState.currentState = GameState.MENU;
playing.setGameState(GameState.MENU);
}

menu.resetBools();
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/cn/com/twoke/game/ui/MenuButton.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ public void applyGameState() {
GameState.currentState = state;
}

public GameState getState() {
return state;
}

public void resetBools() {
mousePressed = false;
Expand Down
Loading

0 comments on commit aa81ad1

Please sign in to comment.