Skip to content

Commit

Permalink
add new sound effect when key is pressed
Browse files Browse the repository at this point in the history
  • Loading branch information
creme332 committed Dec 17, 2023
1 parent 201e957 commit 3bd2103
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/github/creme332/utils/SettingsManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

0 comments on commit 3bd2103

Please sign in to comment.