package view.sound; import javax.sound.sampled.*; import java.io.IOException; import java.net.URL; import java.util.EnumMap; public class SoundManager{ private static SoundManager instance; private EnumMap soundMap; public void stopLoopSound(SOUNDS sound) { soundMap.get(sound).stop(); } public void setVolume(Clip clip, float percent) { if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) { FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); float min = gainControl.getMinimum(); // usually -80.0f float max = gainControl.getMaximum(); // usually 6.0f or 0.0f // Convert percent (0–100) to decibel scale float range = max - min; float gain = (range * percent / 100f) + min; gainControl.setValue(gain); } else { System.err.println("Volume control not supported for this clip."); } } public void setVolume(float volume) { soundMap.forEach((sound, clip) -> { setVolume(clip, volume); }); } public enum SOUNDS { CLICK, MOVING_BUSH, VILLAGER } private SoundManager() { soundMap = new EnumMap<>(SOUNDS.class); } public void loadAllSounds(){ SoundManager.getInstance().loadSound(SoundManager.SOUNDS.CLICK, "sound/click.wav"); SoundManager.getInstance().loadSound(SoundManager.SOUNDS.VILLAGER, "sound/villager.wav"); SoundManager.getInstance().loadSound(SoundManager.SOUNDS.MOVING_BUSH, "sound/moving_bush.wav"); } public void loopSound(SOUNDS sound){ Clip clip = soundMap.get(sound); if(clip != null){ if(clip.isRunning()){ clip.stop(); }else{ clip.loop(Clip.LOOP_CONTINUOUSLY); } } } public static SoundManager getInstance() { if (instance == null) { instance = new SoundManager(); } return instance; } public void loadSound(SOUNDS sound, String resourcePath) { try { URL soundURL = getClass().getClassLoader().getResource(resourcePath); if (soundURL == null) { System.err.println("Resource not found: " + resourcePath); return; } AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundURL); Clip clip = AudioSystem.getClip(); clip.open(audioStream); soundMap.put(sound, clip); } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { System.err.println("Failed to load sound " + sound + ": " + e.getMessage()); } } public void playSound(SOUNDS sound) { Clip clip = soundMap.get(sound); if (clip != null) { if (clip.isRunning()) { clip.stop(); } clip.setFramePosition(0); clip.start(); } else { System.err.println("Sound " + sound + " wurde nicht geladen."); } } public void unloadAllSounds() { for (Clip clip : soundMap.values()) { clip.close(); } soundMap.clear(); } }