Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the useSound hook with multiple audio files

Hi I’m trying to play a different mp3 sound on hover and then stop the sound when the mouse leaves. I installed the use-sound library but I can’t figure out how to use it with more than one audio file.

If I rename the play function into playAudio1 for example I can make useSound play the right audio file, but I can’t figure out how to stop the correct audio file. I was thinking is there a way to assign the "stop" function in each hook to a different variable name, so I can reference it below in the onMouseLeave event.

The code below gives me an error because I have two identical "stop" functions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, { useState} from "react";
import Audio1 from "../public/mp3/audio1.mp3";
import Audio2 from "../public/mp3/audio2.mp3";
import useSound from "use-sound";

function Home() {
   const [hoverAudio1, setHoverAudio1] = useState(false);
   const [hoverAudio2, setHoverAudio2] = useState(false);

   const [playAudio1, { stop }] = useSound(Audio1, {
    volume: 0.5,
   });
   const [playAudio2, { stop }] = useSound(Audio2, {
    volume: 0.5,
   });

   return (
      <div
          onMouseEnter={() => {
            setHoverAudio1(true);
            playAudio1();
          }}
          onMouseLeave={() => {
            setHoverAudio1(false);
            stop();
          }}
        >
      </div>
      <div
          onMouseEnter={() => {
            setHoverAudio2(true);
            playAudio2();
          }}
          onMouseLeave={() => {
            setHoverAudio2(false);
            stop();
          }}
        >
      </div>
    )}

>Solution :

Instead of [playAudio1, {stop}] you should use [playAudio1, stopAudio1] to get the return values from the hook. Then you can access the stop function with stopAudio1.stop().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading