From 296401f4725def2652acb8abdd95a9caf32e517d Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Thu, 9 Apr 2020 14:24:52 +1000 Subject: [PATCH] Updated stream to only show interaction banner when autoplay was unsuccesful --- src/components/Nickname.js | 39 +++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/src/components/Nickname.js b/src/components/Nickname.js index f06f570..5600ab4 100644 --- a/src/components/Nickname.js +++ b/src/components/Nickname.js @@ -4,7 +4,7 @@ import { Text, IconButton, Box } from "theme-ui"; import Banner from "./Banner"; function Nickname({ nickname, stream }) { - const [streamMuted, setStreamMuted] = useState(true); + const [streamMuted, setStreamMuted] = useState(false); const [showStreamInteractBanner, setShowStreamInteractBanner] = useState( false ); @@ -13,10 +13,33 @@ function Nickname({ nickname, stream }) { useEffect(() => { if (audioRef.current) { audioRef.current.srcObject = stream; - setShowStreamInteractBanner(true); + // Try and auto play the audio + audioRef.current + .play() + .then(() => { + // Played fine + }) + .catch(() => { + // Unable to autoplay + setStreamMuted(true); + setShowStreamInteractBanner(true); + }); } }, [stream]); + function toggleMute() { + if (audioRef.current) { + if (streamMuted) { + audioRef.current.play().then(() => { + setStreamMuted(false); + setShowStreamInteractBanner(false); + }); + } else { + setStreamMuted(true); + } + } + } + return ( <> { if (stream) { - setStreamMuted(!streamMuted); - setShowStreamInteractBanner(false); + toggleMute(); } }} > @@ -64,9 +86,7 @@ function Nickname({ nickname, stream }) { )} - {stream && ( - { - setStreamMuted(false); - setShowStreamInteractBanner(false); - }} + onClick={toggleMute} >