package ruscz.game.gameOfProd.Sounds; import ruscz.game.gameOfProd.Windows.WindowOfFreeMove; import javax.sound.sampled.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Scanner; /** * This class handles all sounds being played in the game */ public class SoundManager { private FloatControl gainControl; private Clip clip; private int delay; private HashMap soundMap; public SoundManager() { this.delay = 0; } /** * @param file is name of file * Parses sound map for different entities (currently only for doors) */ public void loadSoundMap(String file) { try { File mapFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + file + "-tileset.txt"); Scanner scanner = new Scanner(mapFile); soundMap = new HashMap<>(); while (scanner.hasNextLine()) { String[] data = scanner.nextLine().split(" "); if (data[0].equals("")) { if (data[1].equals("DOOR")) { soundMap.put("doorOpen", data[2]); soundMap.put("doorClose", data[3]); soundMap.put("doorLocked", data[4]); } else if (data[1].contains("WALK")) { soundMap.put("walk", data[2]); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * @param name is sound name * @param volume is designated volume os float * Plays sound once */ public void playSound(String name, float volume){ AudioInputStream audioIn; try { audioIn = AudioSystem.getAudioInputStream(new File("src/main/resources/sounds/" + name)); clip = AudioSystem.getClip(); if (clip != null) { clip.open(audioIn); } if (clip != null) { gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(volume); clip.start(); } } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } /** * @param name is sound name * @param delay is timer delay in milliseconds * @param volume is designated volume as float * Plays sound repeatedly after delay */ public void playSoundRepeatedly(String name, int delay, float volume) { if (this.delay == delay) { AudioInputStream audioIn; try { audioIn = AudioSystem.getAudioInputStream(new File("src/main/resources/sounds/" + name)); clip = AudioSystem.getClip(); clip.open(audioIn); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(volume); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } this.delay = 0; } else if (this.delay == delay-1) { if (clip != null) { clip.stop(); clip.flush(); } this.delay++; } else { this.delay++; } } public HashMap getSoundMap() { return soundMap; } }