'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.
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 1:[1]
You can rename destructured keys:
const [playAudio1, { stop: stopAudio1 }] = useSound(Audio1, {
volume: 0.5,
});
const [playAudio2, { stop: stopAudio2 }] = useSound(Audio2, {
volume: 0.5,
});
return (
<div
onMouseEnter={() => {
setHoverAudio1(true);
playAudio1();
}}
onMouseLeave={() => {
setHoverAudio1(false);
stopAudio1();
}}
></div>
<div
onMouseEnter={() => {
setHoverAudio2(true);
playAudio2();
}}
onMouseLeave={() => {
setHoverAudio2(false);
stopAudio2();
}}
></div>
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smac89 |
