-
Notifications
You must be signed in to change notification settings - Fork 2
/
scripts.js
108 lines (94 loc) · 2.7 KB
/
scripts.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const types = {
pink: "pink",
brown: "brown",
white: "white",
}
const timerInput = document.getElementById("timer");
const useTimer = (callback, ms) => {
let intervalId;
function intervalWrapper(...args) {
intervalId = setInterval(() => callback(...args), ms);
}
function clearIntervalWrapper() {
clearInterval(intervalId);
}
return [intervalWrapper, clearIntervalWrapper];
}
function updateTimerInput(value) {
const hours = Math.floor(value / 3600);
const minutes = Math.floor((value % 3600) / 60);
const seconds = value % 60;
timerInput.value = `${ padZero(hours) }:${ padZero(minutes) }:${ padZero(
seconds) }`;
}
async function handleStartNoise(type) {
const durationInSeconds = getUserDuration();
if (audioContext) {
await handleStopNoise();
}
if (durationInSeconds) {
await generateNoise(type);
startNoiseTimer();
} else {
await generateNoise(type);
}
}
async function handleStopNoise() {
await audioContext.close();
audioContext = null;
stopNoiseTimer();
}
const noiseTimer = () => {
let duration = getUserDuration();
duration--;
if (duration <= 0) {
handleStopNoise();
}
updateTimerInput(duration);
}
const [startNoiseTimer, stopNoiseTimer] = useTimer(noiseTimer, 1000)
const getUserDuration = () => {
const duration = getDurationInSeconds(timerInput.value);
return duration
}
let audioContext;
const generateNoise = async (type) => {
audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 96000 });
await audioContext.audioWorklet.addModule("RandomNoiseProcessor.js");
const randomNoiseNode = new AudioWorkletNode(
audioContext,
"RandomNoiseProcessor",
{
processorOptions: {
type,
}
}
);
randomNoiseNode.connect(audioContext.destination);
}
function getDurationInSeconds(timeValue) {
const [hours, minutes, seconds] = timeValue.split(":").map(Number);
const duration = (hours * 60 * 60) + (minutes * 60) + (seconds || 0)
return duration
}
function padZero(number) {
return number < 10 ? `0${number}` : number;
}
const theme = localStorage.getItem('theme')
const toggle = document.getElementById('toggle')
const setTheme = (theme) => {
if (!theme) {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)')
toggle.checked = prefersDark.matches
} else {
toggle.checked = theme === 'dark'
}
}
setTheme(theme)
const handleToggle = () => {
if (toggle.checked) {
localStorage.setItem('theme', 'dark')
} else {
localStorage.setItem('theme', 'light')
}
}