-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlarmClock.java
More file actions
68 lines (58 loc) · 2.06 KB
/
Copy pathAlarmClock.java
File metadata and controls
68 lines (58 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.File;
import java.io.IOException;
import java.time.LocalTime;
import java.util.Scanner;
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;
public class AlarmClock implements Runnable {
private final LocalTime alarmTime;
private final String filePath;
private final Scanner scanner;
AlarmClock(LocalTime alarmTime, String filePath, Scanner scanner){
this.alarmTime = alarmTime;
this.filePath = filePath;
this.scanner = scanner;
}
@Override
public void run(){
while(LocalTime.now().isBefore(alarmTime)){
try {
Thread.sleep(1000);
LocalTime now = LocalTime.now();
int hours = now.getHour();
int minutes = now.getMinute();
int seconds = now.getSecond();
System.out.printf("\r%02d:%02d:%02d", hours, minutes, seconds);
}
catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
}
System.out.println("\nALARM RINGING");
playSound(filePath);
}
private void playSound(String filePath){
File audioFile = new File(filePath);
try(AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile)){
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
System.out.print("Press ENTER to stop the alarm: ");
scanner.nextLine();
clip.stop();
scanner.close();
}
catch(UnsupportedAudioFileException e){
System.out.println("Audio file format is not supported");
}
catch(LineUnavailableException e){
System.out.println("Audio is unavailable");
}
catch(IOException e){
System.out.println("Error reading audio file");
}
}
}