React Audio in 2021
Here’s the short of it (TL;DR)
We cannot play music automatically upon loading an app, Chrome requires a user interaction threshold. We can circumvent this by having a user click a play button instead (one of many solutions). There’s one more barrier before we are able to play music. We also cannot play locally stored music files, the URL you provide must be accessed another way, for example an online storage service or you can use a free file hosting service such as Github
Recently I wanted to play music/audio in my react app. I selected my audio file and thought it couldn’t be that hard. I just have to search for a react library that places sound and I’ll be okay.
So I search up “npm react audio player” and after trying a bunch of packages I found out, none of them would allow me to play any sound upon loading because for some reason in 2016, Google Chrome created a new protocol that prevented music from auto-playing in the background presumably to avoid ads or other media from blasting music out of nowhere taking users by surprise.
Well what do we do now?
After two days of intensive googling, and one answer from my bootcamp instructor I finally figured out how to play music! Without further ado, here’s how to play audio in React 2021 (at least this is one way to do it)
function playSound(url) {
const audio = new Audio(url);
audio.play();
}<button onClick={() => playSound("yourUrlHere")}>Play</button>
But this is not the end! Even though I followed this to a T, I still could not play music. Fortunately the link that my instructor provided for me worked even though my own file didn’t play. This demonstrated to me, that an external or online url can be used to play music but we cannot use an internal or local file for audio. I checked other music players on Github and realized that they didn’t use local files to load their songs but they directly linked it to their own Github page
So what I did was I copied the link address to this raw file on Github and I still used:
<button onClick={() => playSound("yourUrlHere")}>Play</button>
However I replaced “yourUrlHere” with
“https://github.com/2seanz/phase-3-codenames/blob/main/frontend/src/components/PinkSweat-AtMyWorstfeatKehlani.mp3?raw=true"
And it totally worked!