-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrumkit.js
executable file
·77 lines (65 loc) · 2.56 KB
/
drumkit.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
async function cacheSounds() {
const soundsCache = await caches.open('soundsCache')
const soundUrls = [
'/sounds/boom.wav',
'/sounds/clap.wav',
'/sounds/hihat.wav',
'/sounds/kick.wav',
'/sounds/openhat.wav',
'/sounds/ride.wav',
'/sounds/snare.wav',
'/sounds/tink.wav',
'/sounds/tom.wav',
]
soundsCache.addAll(soundUrls)
}
async function playSound(e) {
// <audio data-key="KeyA" src="sounds/clap.wav"></audio>
// <audio data-key="KeyS" src="sounds/hihat.wav"></audio>
// <audio data-key="KeyD" src="sounds/kick.wav"></audio>
// <audio data-key="KeyF" src="sounds/openhat.wav"></audio>
// <audio data-key="KeyG" src="sounds/boom.wav"></audio>
// <audio data-key="KeyH" src="sounds/ride.wav"></audio>
// <audio data-key="KeyJ" src="sounds/snare.wav"></audio>
// <audio data-key="KeyK" src="sounds/tom.wav"></audio>
// <audio data-key="KeyL" src="sounds/tink.wav"></audio>
let audio
let key
if (e.type === 'click') {
audio = document.querySelector(`audio[data-key="${e.target.dataset.key}"]`)
key = document.querySelector(`.key[data-key="${e.target.dataset.key}"]`)
} else {
// audio = document.querySelector(`audio[data-key="${e.code}"]`)
const sound = await caches.open('soundsCache')
console.log(`sounds cache: ${sound.keys()}`)
audio = await sound.match('/sounds/clap.wav') // returns a response object (it's like doing a fetch call)
console.log(`audio arraybuffer: ${audio.arrayBuffer()}`)
console.log(`audio blob: ${audio.blob()}`)
// audioRes = await audio.json()
// console.log(`audio res: ${audioRes}`)
// console.log(`audio url: ${audio}`)
key = document.querySelector(`.key[data-key="${e.code}"]`)
}
console.log(`event: ${e}`)
const newAudio = new Audio(audio)
newAudio.play()
// const audio = document.querySelector(`audio[data-key="${e.code}"]`)
// const key = document.querySelector(`.key[data-key="${e.code}"]`)
// if (!audio) return //stop function from running
// audio.currentTime = 0 //start at beginning of audio file
// // audio.url.play()
// key.classList.add('playing')
}
function removeTransition(e) {
if (e.propertyName !== 'transform') return
this.classList.remove('playing')
}
const keys = document.querySelectorAll('.key')
for (const key of keys) {
key.addEventListener('transitionend', removeTransition)
key.addEventListener('click', playSound)
}
// This does same as the above for of loop
// keys.forEach(key => key.addEventListener('transitionend', removeTransition))
cacheSounds()
window.addEventListener('keydown', playSound)