how to use many sounds using useSound - React Js

986 Views Asked by At

Sorry if the title is a bit confusing. Basically I want to play a sound if a user clicks a key, and if they click again it will play another sound.

The setup could look like.

import useSound from 'use-sound';
const Home = () =>  {
    const soundList = [assets.sounds.click1,assets.sounds.click2]
    const [play] = useSound(soundList);// this seems to take one argument.
    function onUserInputChange(e){
        play(// random choice from soundList)
    }
}

How might I be able to pass and argument into play to play audio?

1

There are 1 best solutions below

3
Mario Petrovic On

You can pass from the parent url of the sound to the child and modify parent's state after click:

import useSound from 'use-sound';
import { useState } from 'react'; 

const soundList = [assets.sounds.click1, assets.sounds.click2];

const Home = () => {
  const [soundToPlay, setSoundToPlay] = useState(soundList[0]);

  const onPlay = () => {
    setSoundToPlay(soundList[Math.round(Math.random() * soundList.length)]);
  };

  return <PlayComponent soundUrl={soundToPlay} onPlay={onPlay} />;
};

const PlayComponent = ({ soundUrl, onPlay }) => {
  const [play] = useSound(soundUrl);

  function onUserInputChange(e) {
    play();

    onPlay();
  }

  return <button onClick={onUserInputChange}>Play</button>;
};

*NOTE I guess you wanted to put assets.sounds.click2 instead of assets.sounds.click1 as a second array item