|
| 1 | +import java.time.LocalTime; |
| 2 | +import java.util.Scanner; |
| 3 | + |
| 4 | +import javax.sound.sampled.AudioInputStream; |
| 5 | +import javax.sound.sampled.AudioSystem; |
| 6 | +import javax.sound.sampled.Clip; |
| 7 | +import javax.sound.sampled.LineUnavailableException; |
| 8 | +import javax.sound.sampled.UnsupportedAudioFileException; |
| 9 | + |
| 10 | +import java.awt.Toolkit; |
| 11 | +import java.io.File; |
| 12 | +import java.io.IOException; |
| 13 | + |
| 14 | +public class AlarmClock implements Runnable{ |
| 15 | + |
| 16 | + private final LocalTime alarmTime; |
| 17 | + private final String filePath; |
| 18 | + private final Scanner scanner; |
| 19 | + |
| 20 | + AlarmClock(LocalTime alarmTime, String filePath, Scanner scanner) { |
| 21 | + this.alarmTime = alarmTime; |
| 22 | + this.filePath = filePath; |
| 23 | + this.scanner = scanner; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void run() { |
| 28 | + while(LocalTime.now().isBefore(alarmTime)) { |
| 29 | + try { |
| 30 | + Thread.sleep(1000); |
| 31 | + |
| 32 | + LocalTime now = LocalTime.now(); |
| 33 | + int hours = now.getHour(); |
| 34 | + int minutes = now.getMinute(); |
| 35 | + int seconds = now.getSecond(); |
| 36 | + |
| 37 | + System.out.printf("\r%02d:%02d:%02d", hours, minutes, seconds); |
| 38 | + } catch (InterruptedException e) { |
| 39 | + System.out.println("Thread was interrupted. "); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + System.out.println("\n*ALARM NOISES*"); |
| 44 | + Toolkit.getDefaultToolkit().beep(); |
| 45 | + playSound(filePath); |
| 46 | + } |
| 47 | + |
| 48 | + private void playSound(String filePath) { |
| 49 | + File audioFile = new File(filePath); |
| 50 | + |
| 51 | + try (AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile)){ |
| 52 | + Clip clip = AudioSystem.getClip(); |
| 53 | + clip.open(audioStream); |
| 54 | + clip.start(); |
| 55 | + |
| 56 | + System.out.print("Press Enter to stop the alarm"); |
| 57 | + scanner.nextLine(); |
| 58 | + |
| 59 | + clip.stop(); |
| 60 | + scanner.close(); |
| 61 | + } catch (UnsupportedAudioFileException e) { |
| 62 | + System.out.println("Unsupported file."); |
| 63 | + } catch (IOException e) { |
| 64 | + System.out.println("Error reading audio file."); |
| 65 | + } catch (LineUnavailableException e) { |
| 66 | + System.out.println("Audio is Unavailable"); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments