ZacharyFolk / sandbox

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

Sounds rewrite #56

Closed ZacharyFolk closed 6 months ago

ZacharyFolk commented 1 year ago

Need to make sounds cleaner and able to mute when switch away from a page. Some ideas from chatGPT

const sound1 = new Audio('./sound1.mp3');
const sound2 = new Audio('./sound2.mp3');

const playSound = (id) => {
  switch(id) {
    case '1':
      sound1.play();
      break;
    case '2':
      sound2.play();
      break;
    default:
      console.log('Invalid Sound ID');
  }
}

playSound('1');  // Plays sound1
playSound('2');  // Plays sound2
playSound('3');  // Invalid Sound ID
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const MuteAudioOnRouteChange = () => {
  const location = useLocation();

  useEffect(() => {
    const audio = document.getElementById('audio');
    if (audio) {
      audio.muted = true;
    }
  }, [location.pathname]);

  return null;
};

export default MuteAudioOnRouteChange;

When you create an HTMLAudioElement, you can assign it an ID to easily reference it later on, like this:

const themesong = new Audio('./cagematch_assets/sounds/psykick.mp3');
themesong.id = "themesong";

With an ID, you can easily control the audio with JavaScript, for example:

const audioElement = document.getElementById("themesong");

audioElement.play();
audioElement.pause();
audioElement.volume = 0.5;

Associating audio with an ID allows you to have multiple instances of audio on the same page, and reference them individually by their unique ID. This can be useful if you want to control multiple audio sources at different times, for example, to pause, resume, or stop an individual audio source, or to check if it has finished playing or not. By giving each audio source a unique ID, you can easily reference it in your JavaScript code and perform actions on it as needed.

ZacharyFolk commented 6 months ago

This was done with cagematch, might still have issues but could track them there insted. See #17 for more details on those changes.