react-frequency
Version:
A simple React component and hook which creates a frequency and play it !
94 lines (86 loc) • 3.01 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function useFrequency({ type = 'center', oscillator = 'sine', gain = 1, hz, }) {
const [playing, setPlaying] = React.useState(false);
const ctxRef = React.useRef();
const o = React.useRef();
const gL = React.useRef();
const gR = React.useRef();
React.useEffect(() => {
const AudioContext = window.AudioContext || window.webkitAudioContext;
const ctx = new AudioContext();
const oscillator = ctx.createOscillator();
const gainL = ctx.createGain();
const gainR = ctx.createGain();
const m = ctx.createChannelMerger(2);
oscillator.connect(gainL);
oscillator.connect(gainR);
gainR.connect(m, 0, 1);
gainL.connect(m, 0, 0);
m.connect(ctx.destination);
oscillator.start();
o.current = oscillator;
gL.current = gainL;
gR.current = gainR;
ctxRef.current = ctx;
ctx.suspend();
return () => {
m.disconnect(ctx.destination);
ctx.close();
};
}, []);
React.useEffect(() => {
if (o.current)
o.current.type = oscillator;
}, [oscillator]);
React.useEffect(() => {
if (o.current)
o.current.frequency.value = hz;
}, [hz]);
React.useEffect(() => {
if (gL.current)
gL.current.gain.value = type === 'left' || type === 'center' ? gain : 0;
if (gR.current)
gR.current.gain.value = type === 'right' || type === 'center' ? gain : 0;
}, [type, gain]);
const toggle = () => {
var _a, _b;
if (playing)
(_a = ctxRef.current) === null || _a === void 0 ? void 0 : _a.suspend();
else
(_b = ctxRef.current) === null || _b === void 0 ? void 0 : _b.resume();
setPlaying((play) => !play);
};
const start = () => {
var _a;
if (!playing)
(_a = ctxRef.current) === null || _a === void 0 ? void 0 : _a.resume();
setPlaying(true);
};
const stop = () => {
var _a;
if (playing)
(_a = ctxRef.current) === null || _a === void 0 ? void 0 : _a.suspend();
setPlaying(false);
};
return { toggle, start, stop, playing };
}
const Frequency = ({ type = 'center', oscillator = 'sine', gain = 1, hz, }) => {
const { start, stop } = useFrequency({
type,
oscillator,
gain,
hz,
});
React.useEffect(() => {
start();
return stop;
}, [start, stop]);
return React__default["default"].createElement(React__default["default"].Fragment, null);
};
exports.Frequency = Frequency;
exports.useFrequency = useFrequency;
//# sourceMappingURL=index.js.map