-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
100 lines (84 loc) · 2.65 KB
/
app.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
function playSound(e) {
const key =
e.type === "click"
? e.target.closest(".key")
: document.querySelector(`.key[data-key="${e.keyCode}"]`);
const audio = document.querySelector(
`audio[data-key="${key ? key.getAttribute("data-key") : e.keyCode}"]`
);
if (!audio) return;
if (isClosedOrFootHiHat(audio)) stopOpenHiHat();
audio.currentTime = 0;
audio.play();
// If the crash is played, also play the kick
if (audio.getAttribute("data-key") === "74") {
// 74 is the keyCode for "J" (crash)
const kickAudio = document.querySelector('audio[data-key="68"]'); // 68 is the keyCode for "D" (kick)
if (kickAudio) {
kickAudio.currentTime = 0;
kickAudio.play();
}
}
key.classList.add("playing");
}
function removePlayingClass(e) {
if (e.propertyName !== "transform") return;
this.classList.remove("playing");
}
function handleKeyUp(e) {
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
if (key) key.classList.remove("playing");
}
function isClosedOrFootHiHat(audio) {
const HIHAT_AUDIO_KEY = "70";
const HIHAT_FOOT_AUDIO_KEY = "84";
const currentAudioKey = audio.getAttribute("data-key");
return (
currentAudioKey == HIHAT_AUDIO_KEY ||
currentAudioKey == HIHAT_FOOT_AUDIO_KEY
);
}
function stopOpenHiHat() {
const OPEN_HIHAT_AUDIO_KEY = "72";
const openHiHatAudio = document.querySelector(
`audio[data-key="${OPEN_HIHAT_AUDIO_KEY}"]`
);
if (isPlaying(openHiHatAudio)) stopAudio(openHiHatAudio);
}
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
function isPlaying(audio) {
return !audio.paused;
}
function handleTouch(e) {
e.preventDefault();
const touch = e.changedTouches[0];
const key = document.elementFromPoint(touch.clientX, touch.clientY);
if (key && key.classList.contains("key")) {
playSound({ target: key });
}
}
const keys = document.querySelectorAll(".key");
keys.forEach((key) => {
key.addEventListener("transitionend", removePlayingClass);
key.addEventListener("click", playSound);
});
// Event listeners
window.addEventListener("keydown", playSound);
window.addEventListener("keyup", handleKeyUp);
// Add touch event listeners
const keysContainer = document.querySelector(".keys");
keysContainer.addEventListener("touchstart", handleTouch);
keysContainer.addEventListener("touchend", (e) => {
e.preventDefault();
keys.forEach((key) => key.classList.remove("playing"));
});
// Prevent default touch behavior on the entire document
document.body.addEventListener("touchstart", (e) => e.preventDefault(), {
passive: false,
});
document.body.addEventListener("touchend", (e) => e.preventDefault(), {
passive: false,
});