-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-pad-controller.ts
More file actions
61 lines (53 loc) · 1.5 KB
/
use-pad-controller.ts
File metadata and controls
61 lines (53 loc) · 1.5 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
import { useCallback } from 'react';
import { useActivePads } from './use-pad-controller.use-active-pads';
import { usePadKeyListeners } from './use-pad-controller.use-pad-key-listeners';
import type { PadId } from '../types';
import { PAD_SCHEMA } from '../config';
import * as Tone from 'tone';
const NOTE_DURATION_S = 0.3;
const NOW_BUFFER_S = 0.032;
export const userSynth = new Tone.Synth().toDestination();
export type PadController = ReturnType<typeof usePadController>;
export const usePadController = ({
onUserPadDown,
disabled,
}: {
onUserPadDown: (padId: PadId) => void;
disabled: boolean;
}) => {
const { activePads, setPadActive, setPadInactive } = useActivePads();
const userPadDown = useCallback(
(padId: PadId) => {
if (disabled) {
return;
}
setPadActive(padId);
userSynth.triggerAttackRelease(
PAD_SCHEMA[padId].tone,
NOTE_DURATION_S,
// schedule a little in advance to prevent pops
// https://github.com/Tonejs/Tone.js/wiki/Performance#scheduling-in-advance
Tone.getContext().currentTime + NOW_BUFFER_S,
);
onUserPadDown(padId);
},
[disabled, onUserPadDown, setPadActive],
);
const userPadUp = useCallback(
(padId: PadId) => {
setPadInactive(padId);
},
[setPadInactive],
);
const padKeyListeners = usePadKeyListeners({
onKeydown: userPadDown,
onKeyup: userPadUp,
disabled,
});
return {
activePads,
userPadDown,
userPadUp,
padKeyListeners,
};
};