Reputation: 37
I'm facing one difficulty. I'm working on custom video player and I'm trying to check with useEffect whether video source has video (it opens a link, but never starts). Here is a link with the video http://media.xiph.org/mango/tears_of_steel_1080p.webm
What I want to do is to check for 5 seconds whether video can be loaded and if not - change the isLoaded state to false, block controls and if in 5 seconds it's not solved - redirect to error route (or console.log for instance). If everything is fine and everything loads - change isLoaded to true and start video right after it's available.
I can check whether videoRef's current.duration is not equal to 0 or current.networkState, but I don't know how to check it for 5 seconds and start if everything is allright.
Here is my code:
const PlayerScreen = (props) => {
const [isPlaying, setIsPlaying] = useState(false);
const [isLoaded, setIsLoaded] = useState(false);
const videoRef = useRef(null);
useEffect(() => {
const video = videoRef.current;
video.oncanplay = () => {
setIsPlaying(true);
video.play();
};
video.onplay = () => {
setIsPlaying(true);
};
video.onpause = () => {
setIsPlaying(false);
};
video.ontimeupdate = () => {
if (video.currentTime !== 0) {
handleTimeElapsed();
handleProgress();
}
};
return () => {
video.oncanplaythrough = null;
video.onplay = null;
video.onpause = null;
video.ontimeupdate = null;
};
}, []);
const {
film: {
previewImg,
videoSrc
},
} = props;
return (
<div className="player">
<video
className="player__video"
ref={videoRef}
src={videoSrc} // http://media.xiph.org/mango/tears_of_steel_1080p.webm
poster={previewImg}
/>
</div>)
}
Hope you can help. Thanks!
Upvotes: 0
Views: 1641
Reputation: 674
I made some tests to see how you can handle your state if a video is unavaible
in your useEffect make a requests to sees if there is a network error or not and set a timeout to avoid the fetch time to be infinite.
React.useEffect(() => {
(async () => {
try {
const result = await Axios.get(
"http://media.xiph.org/mango/tears_of_steel_1080p.webm",
{ timeout: 5000}
);
// Do something here
} catch (e) {
console.log("The link is not avaible", e.message);
// Do something here
}
})();
}, []);
If there is no error in your fetch, The useEffect will not catch an error and you can write your code
Upvotes: 1