forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsequence-02.js
More file actions
93 lines (84 loc) · 2.59 KB
/
sequence-02.js
File metadata and controls
93 lines (84 loc) · 2.59 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
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
/* global AudioContext, XMLHttpRequest, requestAnimationFrame */
function start () {
window.AudioContext = window.AudioContext || window.webkitAudioContext
const context = new AudioContext()
function loadAudio (url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', url, true)
request.responseType = 'arraybuffer'
// Decode asynchronously
request.onload = function () {
context.decodeAudioData(request.response, function (buffer) {
resolve(buffer)
}, reject)
}
request.send()
})
}
function playSound (buffer) {
const source = context.createBufferSource() // creates a sound source
source.buffer = buffer // tell the source which sound to play
source.connect(context.destination) // connect the source to the context's destination (the speakers)
source.start(0) // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
}
let hithatBuffer
let kickBuffer
let tinkBuffer
loadAudio('sounds/hihat.wav').then((buffer) => {
hithatBuffer = buffer
})
.then(() => {
return loadAudio('sounds/kick.wav').then((buffer) => {
kickBuffer = buffer
})
})
.then(() => {
return loadAudio('sounds/tink.wav').then((buffer) => {
tinkBuffer = buffer
})
})
.then(() => {
const beatsPerSecond = 5
let seqIndex = 0
function draw () {
setTimeout(() => {
requestAnimationFrame(draw)
if (seqIndex % 8 === 0) {
playSound(hithatBuffer)
playSound(kickBuffer)
}
if (seqIndex % 8 === 1) {
playSound(hithatBuffer)
}
if (seqIndex % 8 === 2) {
playSound(hithatBuffer)
playSound(tinkBuffer)
}
if (seqIndex % 8 === 3) {
playSound(hithatBuffer)
playSound(kickBuffer)
}
if (seqIndex % 8 === 4) {
playSound(hithatBuffer)
playSound(kickBuffer)
}
if (seqIndex % 8 === 5) {
playSound(hithatBuffer)
playSound(tinkBuffer)
}
if (seqIndex % 8 === 6) {
playSound(hithatBuffer)
}
if (seqIndex % 8 === 7) {
playSound(hithatBuffer)
playSound(kickBuffer)
}
seqIndex++
}, 1000 / beatsPerSecond)
}
draw()
})
}
window.onload = start