-
Notifications
You must be signed in to change notification settings - Fork 97
/
DrumMachine.js
89 lines (77 loc) · 1.85 KB
/
DrumMachine.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
import React from 'react';
import styled from 'styled-components';
import useSound from '@';
import Button from '../helpers/Button';
import drumSfx from '../sounds/909-drums.mp3';
const useKeyboardBindings = map => {
React.useEffect(() => {
const handlePress = ev => {
const handler = map[ev.key];
if (typeof handler === 'function') {
handler();
}
};
window.addEventListener('keydown', handlePress);
return () => {
window.removeEventListener('keydown', handlePress);
};
}, [map]);
};
function DrumMachine() {
const [play] = useSound(drumSfx, {
sprite: {
kick: [0, 350],
hihat: [374, 160],
snare: [666, 290],
cowbell: [968, 200],
},
});
// Custom hook that listens for 'keydown',
// and calls the appropriate handler function.
useKeyboardBindings({
1: () => play({ id: 'kick' }),
2: () => play({ id: 'hihat' }),
3: () => play({ id: 'snare' }),
4: () => play({ id: 'cowbell' }),
});
return (
<>
<h2>Drum machine</h2>
<PressyButton aria-label="kick" onMouseDown={() => play({ id: 'kick' })}>
1
</PressyButton>
<PressyButton
aria-label="hihat"
onMouseDown={() => play({ id: 'hihat' })}
>
2
</PressyButton>
<PressyButton
aria-label="snare"
onMouseDown={() => play({ id: 'snare' })}
>
3
</PressyButton>
<PressyButton
aria-label="cowbell"
onMouseDown={() => play({ id: 'cowbell' })}
>
4
</PressyButton>
<p>
You can also use your keyboard!
<br />
Type "1" through "4".
</p>
</>
);
}
const PressyButton = styled(Button)`
display: inline-block;
margin: 10px;
transform-origin: center center;
&:active {
transform: scale(1.1);
}
`;
export default DrumMachine;