A React Component for Playing Audio Files in the Browser

A React Component for Playing Audio Files in the Browser
Photo by Sandy Kawadkar / Unsplash

here's a small component I wrote that plays audio files in the browser.

there are three ways it can be used.

  1. on click as feedback
  2. on hover
  3. in background on loop

audio.js

one thing to note is that the volume tends to get loud very quickly, hence its kept at 0.01

play once or on click

to play it once, set loop to false and increment playing by one.

<AudioPlay audio="success.wav" playing={correctGuesses} loop={false}></AudioPlay>

play in loop

to play in loop, set loop to true and playing to true. there is a browser limitation in chrome where it does not allow you to play music unless the user has interacted with the page.

<AudioPlay playing={playing} loop={true} audio="bg.wav"></AudioPlay>

play on hover

we set loop to false and use the onMouseEnter event to update the active state to 1 or 2 or n. this updates the playing prop on AudioPlay.

 <a onMouseEnter={() => handleActive(1)}>
 	<h3>Hover me</h3>
 </a>

<a onMouseEnter={() => handleActive(2)}>
 	<h3>Hover me 2</h3>
 </a>
const [active, setActive] = useState(1);

const handleActive = (item) => {
	setActive(item);
}
<AudioPlay audio="menu-hover.wav" playing={active} loop={false}></AudioPlay>

see it in action at: https://hangman.genboota.com/