"use client";
import { useRef } from "react";
import { Cloudinary } from "@cloudinary/url-gen";
import {
AdvancedVideo,
AdvancedImage,
lazyload,
accessibility,
} from "@cloudinary/react";
import { crop } from "@cloudinary/url-gen/actions/resize";
interface props {
publicId: string;
poster: string;
height?: number | string;
width?: number | string;
controls: boolean;
loop?: boolean;
autoplay: boolean;
muted: boolean;
playsInline?: boolean;
alt?: string;
}
const cld = new Cloudinary({
cloud: { cloudName: "your-cloudinary-cloudname" },
});
export default function MediaComponent({
publicId,
poster,
controls,
loop,
autoplay,
muted,
width,
height,
playsInline,
alt,
}: props) {
const playerRef = useRef<AdvancedVideo | any>();
let shouldPlayVideo;
const videoLoaded = function () {
shouldPlayVideo = true;
if (shouldPlayVideo) {
playerRef.current.videoRef.current?.play();
}
};
const pauseVideo = function () {
playerRef.current.videoRef.current?.pause();
playerRef.current.videoRef.current?.load();
};
return (
<div className="relative group" onMouseLeave={pauseVideo}>
<AdvancedImage
className="relative z-10"
alt={alt}
cldImg={cld
.image(poster)
.setAssetType("video")
.format("auto:image")
.resize(crop(width, height))}
/>
<AdvancedVideo
ref={playerRef}
onLoadedData={videoLoaded}
className="absolute top-0 left-0 opacity-0 z-0 group-hover:z-20 group-hover:opacity-100 transition-opacity duration-700 bg-zinc-900"
loop={loop}
autoPlay={autoplay}
muted={muted}
cldVid={cld.video(publicId).resize(crop(width, height))}
plugins={[lazyload(), accessibility()]}
playsInline={playsInline}
controls={controls}
/>
</div>
);
}
const reels: CloudinaryType[] = await getMedia("reels");
<MediaComponent
autoplay={true}
muted={true}
loop={true}
key={reel.id}
height={1280}
width={720}
publicId={reel.name}
poster={reel.name}
controls={false}
playsInline={true}
alt={`${reel.name.split("/")[1]} reel project`}
/>