Created
September 8, 2024 05:17
-
-
Save nghiepdev/ca848a0ff2e473937ef53ced720852f2 to your computer and use it in GitHub Desktop.
Implementing video auto unmuted unlocking
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 {useRef, useEffect} from 'react'; | |
export function useVideoUnmuted() { | |
const element = useRef<HTMLVideoElement | null>(null); | |
useEffect(() => { | |
const context = new window.AudioContext(); | |
function unmuted() { | |
if (element.current) { | |
element.current.muted = false; | |
} | |
} | |
function unlock() { | |
context.resume().then(unmuted).then(remove); | |
} | |
function remove() { | |
window.removeEventListener('keydown', unlock); | |
window.removeEventListener('click', unlock); | |
window.removeEventListener('touchstart', unlock); | |
window.removeEventListener('touchend', unlock); | |
} | |
if (context.state === 'suspended') { | |
window.addEventListener('click', unlock, false); | |
window.addEventListener('touchstart', unlock, false); | |
window.addEventListener('touchend', unlock, false); | |
window.addEventListener('keydown', unlock, false); | |
return remove; | |
} else if (context.state === 'running') { | |
unmuted(); | |
} | |
}, []); | |
return element; | |
} | |
function App() { | |
const videoElement = useVideoUnmuted(); | |
return ( | |
<video ref={videoElement} muted autoPlay loop playsInline> | |
<source src='/my-video.mp4' /> | |
</video> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment