4828
Sr
stream-together / files
stream-together / hooks / use-agora-virtual-background.ts
2.0 KB
1"use client"; 2 3import VirtualBackgroundExtension, { 4 IVirtualBackgroundProcessor, 5} from "agora-extension-virtual-background"; 6import AgoraRTC, { ICameraVideoTrack } from "agora-rtc-react"; 7import { useCallback, useEffect, useRef, useState } from "react"; 8 9export default function useVirtualBackground({ 10 localCameraTrack, 11}: { 12 localCameraTrack: ICameraVideoTrack | null; 13}) { 14 const extension = useRef(new VirtualBackgroundExtension()); 15 const processor = useRef<IVirtualBackgroundProcessor>(); 16 const [backgroundBlurred, setBackgroundBlurred] = useState(false); 17 18 useEffect(() => { 19 const initializeExtension = async () => { 20 AgoraRTC.registerExtensions([extension.current]); 21 22 if (!extension.current.checkCompatibility()) { 23 console.error("Your browser does not support Virtual background!"); 24 return; 25 } 26 27 if (localCameraTrack && !processor.current) { 28 try { 29 processor.current = extension.current.createProcessor(); 30 await processor.current.init(); 31 localCameraTrack 32 .pipe(processor.current) 33 .pipe(localCameraTrack.processorDestination); 34 } catch (error) { 35 console.error(error); 36 } 37 } 38 }; 39 40 void initializeExtension(); 41 42 return () => { 43 const disableExtension = async () => { 44 processor.current?.unpipe(); 45 localCameraTrack?.unpipe(); 46 await processor.current?.disable(); 47 }; 48 void disableExtension(); 49 }; 50 }, [localCameraTrack]); 51 52 const handleBlurBackground = useCallback(() => { 53 const enableBlur = async () => { 54 if (processor.current?.enabled) { 55 processor.current?.disable(); 56 setBackgroundBlurred(false); 57 } else { 58 processor.current?.setOptions({ 59 type: "blur", 60 blurDegree: 2, 61 }); 62 processor.current?.enable(); 63 setBackgroundBlurred(true); 64 } 65 }; 66 void enableBlur(); 67 }, [processor]); 68 69 return { backgroundBlurred, handleBlurBackground }; 70}