From 4032730b9bfea720e52627329f4cc6752a9ef670 Mon Sep 17 00:00:00 2001 From: Mikayla Dobson Date: Tue, 8 Feb 2022 11:31:57 -0600 Subject: [PATCH] conditional handling for videos without audio --- src/features/video/VideoPlayer.js | 68 ++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 23 deletions(-) diff --git a/src/features/video/VideoPlayer.js b/src/features/video/VideoPlayer.js index e27d6a5..f1928e7 100644 --- a/src/features/video/VideoPlayer.js +++ b/src/features/video/VideoPlayer.js @@ -1,11 +1,12 @@ import { useState, useEffect, useRef } from 'react'; export default function VideoPlayer({data, src}) { + const vidControls = useRef(); const vid = useRef(); const aud = useRef(); // identifies location of video/audio in DOM const [playing, setPlaying] = useState(false); // handles play/pause logic - const [error, setError] = useState(null); + const [audio, setAudio] = useState(null); const crossPostSrc = src; @@ -13,48 +14,69 @@ export default function VideoPlayer({data, src}) { (data.url ? data.url : null); // location within reddit response - useEffect(() => { - const req = new XMLHttpRequest(); - req.open('HEAD', `${url}/DASH_audio.mp4`, true); - req.send(); - if (req.status === 404) { - setError(true); + useEffect(() => { // checks the endpoint where audio may be found + let checking = true; // if the fetch request throws an error, audio is set to null; + const checkForAudio = async() => { // otherwise, audio is set to the endpoint, which is evaluated + try { // below as truthy, and rendered in the page + await fetch(`${url}/DASH_audio.mp4`) + .then((response) => { + let status = response.status; + if (status > 400) { + setAudio(null); + } else { + setAudio(`${url}/DASH_audio.mp4`); + } + }); + } catch(e) { + console.log(e); + } } - if (req.status === 403) { - setError(true); - } - }, [url]); - useEffect(() => { // synchronizes play/pause between two components - if (playing) { // according to section of state - vid.current.play(); - vid.current.currentTime = aud.current.currentTime; + if (checking) { + checkForAudio(); + checking = false; + } + + return () => { + checking = false; + } + }, [url, audio]); + + useEffect(() => { // this section handles simultaneous playback of audio and video + if (!audio) { + return; + } + + if (playing) { + vid.current.play(); // synchronizes play/pause between two components + vid.current.currentTime = aud.current.currentTime; // according to section of state } else if (!playing) { vid.current.pause(); } - }, [playing, aud, vid]); + }, [playing, audio, aud, vid]); return (
{ - !error ? + !audio ? <> - -