Skip to content

Instantly share code, notes, and snippets.

@nghiepdev
Created September 8, 2024 05:17
Show Gist options
  • Save nghiepdev/ca848a0ff2e473937ef53ced720852f2 to your computer and use it in GitHub Desktop.
Save nghiepdev/ca848a0ff2e473937ef53ced720852f2 to your computer and use it in GitHub Desktop.
Implementing video auto unmuted unlocking
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