Skip to content

Instantly share code, notes, and snippets.

@jebeck
Created April 27, 2020 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jebeck/6555c574da38c0a6a9a17b518ce412a3 to your computer and use it in GitHub Desktop.
Save jebeck/6555c574da38c0a6a9a17b518ce412a3 to your computer and use it in GitHub Desktop.
import { useEffect } from 'react';
export function makeGetAudioCtxSingleton() {
let ctx;
function createAudioCtx() {
return new AudioContext();
}
return () => {
if (!ctx) {
ctx = createAudioCtx();
}
return ctx;
};
}
export function useAudioContext({ getAudioCtx }) {
const audioCtx = getAudioCtx();
function pause() {
audioCtx.suspend();
}
function play() {
audioCtx.resume();
}
useEffect(() => {
/** auto-play is very rude */
if (audioCtx.state === 'running') {
audioCtx.suspend();
}
return () => {
audioCtx.close();
};
}, [audioCtx]);
return { audioCtx, pause, play };
}
import React from 'react';
import PropTypes from 'prop-types';
import {
makeGetAudioCtxSingleton,
useAudioContext,
} from '../hooks/useAudioContext';
function AudioContextWrapper({ Component, getAudioCtx, ...rest }) {
const audioCtx = useAudioContext({ getAudioCtx });
return <Component {...audioCtx} {...rest} />;
}
AudioContextWrapper.propTypes = {
Component: PropTypes.func.isRequired,
getAudioCtx: PropTypes.func.isRequired,
};
export function withAudioContext(Component) {
return function AudioContextSingletonWrapper(props) {
return (
<AudioContextWrapper
Component={Component}
getAudioCtx={makeGetAudioCtxSingleton()}
{...props}
/>
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment