diff --git a/src/main/java/com/github/creme332/controller/PlayScreenController.java b/src/main/java/com/github/creme332/controller/PlayScreenController.java index 7158182..a8a06f3 100644 --- a/src/main/java/com/github/creme332/controller/PlayScreenController.java +++ b/src/main/java/com/github/creme332/controller/PlayScreenController.java @@ -4,8 +4,17 @@ import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; import java.util.Timer; import java.util.TimerTask; + +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.Clip; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; @@ -77,6 +86,16 @@ private void dispatchKeyEvent(String keyCommand) { // String.format("Current index = %d. Pressed %s", model.getCursorPos(), // keyCommand)); + // check if sound setting is enabled and play sound if needed + if ((new SettingsManager()).soundActivated()) { + try { + playSound(); + } catch (Exception e) { + // if unable to play sound, print out error but let game go on. + System.out.println(e); + } + } + // when a key is pressed for the first time, start timer if (model.getStartTime() <= 0) { startTimer(); @@ -274,4 +293,13 @@ public void run() { // show text to be typed playScreen.showText(model.getTypeText()); } + + void playSound() + throws MalformedURLException, UnsupportedAudioFileException, IOException, LineUnavailableException { + URL ostFile = PlayScreenController.class.getResource("/tap.wav"); + AudioInputStream audioIn = AudioSystem.getAudioInputStream(ostFile); + Clip clip = AudioSystem.getClip(); + clip.open(audioIn); + clip.start(); + } } diff --git a/src/main/java/com/github/creme332/utils/SettingsManager.java b/src/main/java/com/github/creme332/utils/SettingsManager.java index 9a95601..f57d211 100644 --- a/src/main/java/com/github/creme332/utils/SettingsManager.java +++ b/src/main/java/com/github/creme332/utils/SettingsManager.java @@ -112,4 +112,8 @@ public void setData(String key, String data) { settingDict.get(key).setData(data); } + + public boolean soundActivated() { + return getData("Typing sound").equals("on"); + } }