| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- 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<SOUNDS, Clip> 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();
- }
- }
|