I am working on a virtual piano application, and I’m having a lot of issues with trying to fetch audio files from github. Specifically, I keep getting the errors
Access to fetch at
'https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3'
from origin'http://127.0.0.1:5500'
has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
GET https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3 net::ERR_FAILED 200 (OK)
@ piano.js:57 ready
Uncaught (in promise) TypeError: Failed to fetch at createAudioBuffers (piano.js:57:26) at ready (piano.js:28:26) at piano.js:13:5
In my code, I am simply calling fetch via
const c4AudioURL = "https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3";
const c4AudioFetch = fetch(c4AudioURL);
I am using Live Server on VSCode, so I tried to deploy my site to GH Pages to see if that would fix things, but I still got the errors. I also tried two different CORS proxies, one being crossorigin.me and my code changing to
const c4AudioURL = "https://crossorigin.me/https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3";
and the other changing my code to
const c4AudioURL = "https://corsproxy.io/https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp";
Am I missing something here? I suppose It’s that possible that I’m missing something in my code or in the way I’m using Github, as I’m a pretty inexperience programmer. I’ve been stuck on this for a while, so I appreciate any ideas you might have!
2
Answers
Use local / server-relative paths. For example, say your directory structure looks like this…
With either LiveServer serving this directory or deploying it to Github Pages, you can fetch assets without going cross-origin
That way it will work wherever you run it, as long as you publish your MP3 files when deploying to Github pages. Then you won’t need to worry about CORS at all
The url used for the GET request shown in the post is
returns the same HTML github page returned by opening the
sounds
folder in the main repo, and clicking on the "c4-virtual-piano.mp3" link opened up. It is not a link to the mp3 file.On the "c4-virtual-piano.mp3" HTML page that loads, right click on the button labelled "View raw" and copy the link to the actual mp3 file (or a route to it :-), which can be copy and pasted into the
src
attribute of anaudio
element to play the sound – a 17 second piano note with attack and decay.I suggest looking at the possibility of using a public CDN for downloading project files in production: Should Github be used as a CDN for javascript libraries? could be worth a look at, but contains references to some outdated and now unavailable services.