Created
April 27, 2020 01:21
-
-
Save jebeck/6555c574da38c0a6a9a17b518ce412a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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