diff --git a/apps/common-app/src/App.tsx b/apps/common-app/src/App.tsx index 9bf407505..c877dc619 100644 --- a/apps/common-app/src/App.tsx +++ b/apps/common-app/src/App.tsx @@ -170,7 +170,8 @@ const App: FC = () => { headerTintColor: colors.white, headerBackTitle: 'Back', headerBackAccessibilityLabel: 'Go back', - }}> + }} + > { + const audioContext = useAudioContext(); + const [sampleBuffer, setSampleBuffer] = useState(null); + const [sourceNode, setSourceNode] = useState( + null + ); + const sourceNodeRef = useRef(null); + + useEffect(() => { + sourceNodeRef.current = sourceNode; + }, [sourceNode]); + + const onToggleState = async () => { + if (audioContext.state === 'suspended') { + await audioContext.resume(); + } else { + await audioContext.suspend(); + } + }; + + useEffect(() => { + async function prepareSample() { + const buffer = await audioContext.decodeAudioData(filePath); + setSampleBuffer(buffer); + } + + prepareSample(); + }, [audioContext]); + + const onPlaySample = () => { + if (!sampleBuffer) { + return; + } + + const node = audioContext.createBufferSource(); + node.buffer = sampleBuffer; + node.connect(audioContext.destination); + node.start(); + + setSourceNode(node); + }; + + const onStopSample = () => { + if (!sourceNode) { + return; + } + + sourceNode.stop(); + setSourceNode(null); + }; + + useEffect(() => { + return () => { + if (sourceNodeRef.current) { + sourceNodeRef.current.stop(); + } + }; + }, []); + + return ( + <> + state: {audioContext.state} + +