ZacharyFolk / sandbox

My digital business card, blog, and sandbox for various JS experiments
https://folk.codes
0 stars 0 forks source link

Add mute button to top #17

Closed ZacharyFolk closed 6 months ago

ZacharyFolk commented 1 year ago

idea from chatgpt

import React, { useState, createContext } from 'react';

export const SoundContext = createContext();

export const SoundController = ({ children }) => {
  const [isMuted, setIsMuted] = useState(false);

  const handleMuteClick = () => {
    setIsMuted(prevState => !prevState);
  }

  return (
    <SoundContext.Provider value={{ isMuted, handleMuteClick }}>
      <button onClick={handleMuteClick}>Mute</button>
      {children}
    </SoundContext.Provider>
  );
};

const App = () => {
  return (
    <SoundController>
      <Header />
      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />
      {/* Other routes */}
    </SoundController>
  );
};

const MyComponentThatUseAudio = () => {
  const { isMuted } = useContext(SoundContext);
  const audioRef = useRef(new Audio('./sounds/sound.mp3'));

  useEffect(() => {
    if (isMuted) {
      audioRef.current.pause();
    } else {
      audioRef.current.play();
    }
  }, [isMuted,audioRef]);

  return <audio ref={audioRef} />;
}
ZacharyFolk commented 6 months ago

Did this for the split out game, main site doesn't really have sounds any more. Can reference how I did this mostly in

https://github.com/ZacharyFolk/cagematch/commit/a8d68f0f9af223b13e1995c228b8b68b6640e5a2

and

https://github.com/ZacharyFolk/cagematch/commit/00a9ba6ed3fc73cf938d81b5ed2d28b45455fa48