react-frequency
Version:
A simple React component and hook which creates a frequency and play it !
85 lines (81 loc) • 2.65 kB
JavaScript
import React, { useState, useRef, useEffect } from 'react';
function useFrequency({ type = 'center', oscillator = 'sine', gain = 1, hz, }) {
const [playing, setPlaying] = useState(false);
const ctxRef = useRef();
const o = useRef();
const gL = useRef();
const gR = useRef();
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();
};
}, []);
useEffect(() => {
if (o.current)
o.current.type = oscillator;
}, [oscillator]);
useEffect(() => {
if (o.current)
o.current.frequency.value = hz;
}, [hz]);
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,
});
useEffect(() => {
start();
return stop;
}, [start, stop]);
return React.createElement(React.Fragment, null);
};
export { Frequency, useFrequency };
//# sourceMappingURL=index.js.map