Building an Audio Player in React
In December 2018, Google changed their autoplay policy regarding web audio, requiring the user to interact with the page before any audio is played. There are some exceptions to this based on user preferences (and also some potential workarounds involving the use of iframes), but in the interest of having a cool load screen I’ll show you how I tied that into enabling autoplay in my latest project.
Start by creating a new folder in the src folder of your project called “audio”, and add your audio files to that folder. Then create an AudioPlayer.js component and import each file (in my case I’ll be importing them straight into my Footer component because I only need a very simple player for this project).
Now create a div with id audio-player that contains a self-closing audio tag. The audio tag should also have autoPlay, preload=”true” (must be explicitly set to true), and loop (if desired). Now the src attribute must be set to tell our player what to play, and I’m going to warn you this looks a little messy and there’s probably a more elegant solution, but I’ve had no performance issues with the method seen below.
The song prop is being passed into this component from a tracklist, which is also a pretty simple setup. Basically just state containing a default song and an array of song titles that are being mapped over and given an onClick event that changes the state to that specific song. Make sure that the song state is also being passed into your audio player component.
Now for the autoplay. Basically we need a button for the user to click to enter the page, and a handleEnter method that triggers our load screen to disappear and our audio to play. Mine looks like this:
Now, just add an onClick prop to our enter button that triggers this handleEnter method. Then just set up some basic conditional rendering on your index page that only displays the load screen if entered is false.
And that’s it for a simple audio player with autoPlay. You could also add some buttons by the audio player to trigger audio.pause() or audio.mute() using the same method we used to trigger audio.play(). A full list of audio tag events is available here.