Code explanation
In the above code:
The play
function comes from the useSound
hook (line 7), which is initialized with the sound file specified (hover.mp3
). Make sure to replace hover.mp3
with the correct path to your audio file (line 3), and then you can use the HoverSoundButton
component in your main application to display the button. When the button is hovered over, it will play the sound you specified.
Note: Most browsers restrict audio playback until there’s an initial user interaction, such as a click. This means use-sound
may not play the hover sound until the button is clicked once. After this initial interaction, it should work as expected on subsequent hovers.
Advanced example: Button with hover sound and visual feedback
The use-sound
library enables us to create a button with a sound effect that plays when hovered over. The following example illustrates how to achieve this effect, dynamically triggering the sound by simply hovering over the button. Additionally, this advanced example incorporates both sound and visual feedback, including a color change on hover.