IT/React.js

[React] Video 태그 영상 자동재생

월공 2024. 4. 12. 14:01
728x90
300x250

 

 

영상 백그라운드로 자동재생해야 되게끔 조정을 해야했는데, 될때 있고 안될때 있어서 이것저것 쑤셔넣어서 실험하다가
아마 아래껄로 진행 할듯 함
위 에러는 "the play() request was interrupted by a call to pause()"  뭔가 아직 준비 안됐는데 어거지로 작동시키려해서 나는 에러 같아서 settimeout 추가
그 이후로는 에러 발생 안했음

const videoRef = useRef(null);

...생략...

useEffect(() => {
    setTimeout(()=>{        
        const video = videoRef.current;
        if (video) {
        const playPromise = video.play();
        if (playPromise !== undefined) {
            playPromise.then(_ => {                
                console.log('성공')              
            }).catch(error => {
                console.log('실패')              
                console.error('Video playback failed:', error);
            });
        } 
        }
        return () => {          
        if (video) {
            //console.log('리턴')
            video.pause();
            video.currentTime = 0;
        }
        };
    }, 1000)
}, []);

...생략...

<VideoContainer>
    <Video
        ref={videoRef}
        autoPlay
        loop
        webkit-playsinline="true"
        muted
        playsInline
        preload="auto"                
    >        
        <source src="/images/bg/pv_saga.mp4" type="video/mp4" />
        {/* <source src="img/video.webm" type="video/webm" /> */}
        Your browser is not supported!
    </Video>
</VideoContainer>

 

사실 useEffect 까지 굳이 안쓰고도 위 처럼 넣은 Video 옵션들만으로도 충분히 영상 재생은 잘 되는듯한데 이 부분은 좀 더 테스트 진행해봐야 될듯함

728x90
300x250