useSound hook with array of sounds

778 Views Asked by At

I want to use this useSound hook with an array of sounds. I am able to play the sounds as described in a typical example in the docs, and also a single sound played within a separate function (which I may be doing incorrectly). But what I ultimately want to do is to play a sound from an array from a separate function. Below is my code showing something close to what I want to accomplish (part 3) if it were working. Here is a codesandbox link. How would I correctly play the sound from an array?

import "./styles.css";
import sound0 from "./audio/sound0.mp3";
import sound1 from "./audio/sound1.mp3";
import sound2 from "./audio/sound2.mp3";
import useSound from "use-sound";

export default function App() {
  // 1. Sound declarations according to typical example (working)
  const [soundEffect0] = useSound(sound0);
  const [soundEffect1] = useSound(sound1);
  const [soundEffect2] = useSound(sound2);

  // 2. Function plays sound (working)
  function playSound() {
    soundEffect0();
  }

  // 3. Desired Method playing sound from array of sounds (not working)
  const [soundEffects] = useSound([sound0, sound1, sound2]);

  function playSoundFromArray(idx) {
    soundEffects[idx]();
  }

  return (
    <div className="App">
      <h2>1. Example Method (working)</h2>
      <button onClick={soundEffect0}>soundEffect0</button>
      <button onClick={soundEffect1}>soundEffect1</button>
      <button onClick={soundEffect2}>soundEffect2</button>

      <h2>2. Playing sound within function (working)</h2>
      <button onClick={playSound}>playSound function</button>

      {/* <h2>3. Desired Method playing sound from array of sounds (not working)</h2>
      <button onClick={playSoundFromArray(0)}>soundEffect0</button> */}
    </div>
  );
}
1

There are 1 best solutions below

0
devpolo On

I’m afraid that you are miss understanding how multiple source are supposed to work. You may have a look to this merged PR.

Looks like you cannot play a sound by index (which is what you are trying to do). This is how it works:

const Player = () => {
  const [play] = useSound([soundfile1, soundfile2]);

  return <div onClick={() => play()}>Play</div>;
};