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 onm ouseLeave 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
onm ouseEnter={() => {
setHoverAudio1(true);
playAudio1();
}}
onm ouseLeave={() => {
setHoverAudio1(false);
stop();
}}
>
</div>
<div
onm ouseEnter={() => {
setHoverAudio2(true);
playAudio2();
}}
onm ouseLeave={() => {
setHoverAudio2(false);
stop();
}}
>
</div>
)}
CodePudding user response:
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()
.
CodePudding user response:
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
onm ouseEnter={() => {
setHoverAudio1(true);
playAudio1();
}}
onm ouseLeave={() => {
setHoverAudio1(false);
stopAudio1();
}}
></div>
<div
onm ouseEnter={() => {
setHoverAudio2(true);
playAudio2();
}}
onm ouseLeave={() => {
setHoverAudio2(false);
stopAudio2();
}}
></div>
);