대부분의 브라우저는 "브라우저의 자동 재생 정책" 으로 인하여, 첫 로드시에는 자동재생이 허용되지 않습니다. 따라서 muted 속성을 true 설정하고, 사용자와 상호 작용해서 play 를 할 수 있습니다.
아래 코드는 background-image로 video를 깔고, 별도의 audio파일을 아이콘을 이용하여 ON/OFF 토글하도록 설정한 코드입니다. background-image 는 overlay 처리를 하고, audio 의 음량을 고정시켜서 배경음악으로 만 사용 합니다.
import { useRef, useState } from "react";
import bgVideo from "../assets/background/seokang-background.mp4";
import MainText from "../components/MainText";
import RenderModel from "../components/RenderModel";
import Blocks from "../components/models/Blocks";
import { Volume2, VolumeX } from "lucide-react";
import birds from "../assets/audio/birds.mp3";
const Home = () => {
const audioRef = useRef();
const [isPlaying, setIsPlaying] = useState(false);
const togglePlay = () => {
if (audioRef.current) {
// 볼륨 설정
audioRef.current.volume = 0.4;
if (isPlaying) {
audioRef.current.pause();
} else {
audioRef.current.play().catch((error) => {
console.log(" Error playing audio: ", error);
});
}
setIsPlaying(!isPlaying);
}
};
return (
<main className="relative min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-300 to-slate-500">
<video
className="absolute top-0 left-0 w-full h-full object-cover"
src={bgVideo}
autoPlay
loop
muted
/>
<div className="overlay absolute top-0 left-0 w-full h-full bg-black bg-opacity-80 z-10 flex justify-center pt-2"></div>
<div className="w-full h-screen absolute z-20 flex justify-center items-center">
<MainText />
<RenderModel>
<Blocks />
</RenderModel>
</div>
<div className="fixed bottom-2 right-3 font-thin z-50 ">
<audio ref={audioRef} src={birds} loop />
<button
onClick={togglePlay}
className="border-2 p-1 rounded-full text-white"
>
{isPlaying ? <VolumeX /> : <Volume2 />}
</button>
</div>
</main>
);
};
export default Home;
text-anchor (2) | 2025.01.07 |
---|---|
@apply - tailwind css 에서 사용하는 이유 (1) | 2024.11.28 |
width 를 min() 으로 설정하기 (0) | 2024.11.25 |
video, iframe 비교 (0) | 2024.11.21 |
all: unset 또는 unset, inherit, initial (0) | 2024.10.30 |