search

Home  >  Q&A  >  body text

Fix CORS error playing mp3 files from another website

The problem I'm having is that my React app cannot play audio from other sources and gets a CORS error. Example: https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3

The strange thing is that when I visit https://www.w3schools.com/tags/tag_audio.asp, I enter the above URL and click play.

On my local React app I then get a 302 status and a redirect. The audio tag contains crossOrigin="anonymous" and the url in the src element.

On W3Schools, it redirects somehow and I only get status 206 from the redirected URL.

How to reproduce:

  1. git clone https://github.com/SamTV12345/PodFetch.git
  2. Follow the README instructions in the "Build" section
  3. git checkout origin/development
  4. Add any podcast with more than 5 episodes.
  5. Click CloudIcon

P粉662361740P粉662361740226 days ago392

reply all(1)I'll reply

  • P粉801904089

    P粉8019040892024-04-01 19:41:22

    You need to import the mp3 URL via new Audio(url) instead of XMLHttpRequest to avoid CORS. For example:

    class PlaySound extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          play: false
        };
    
        this.url = "https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3";
        this.audio = new Audio(this.url);
        this.togglePlay = this.togglePlay.bind(this);
      }
    
      togglePlay() {
        const wasPlaying = this.state.play;
        this.setState({
          play: !wasPlaying
        });
    
        if (wasPlaying) {
          this.audio.pause();
        } else {
          this.audio.play();
          setInterval(()=>{
            console.clear();
            let seconds = new Date().getSeconds();
            let points = '.'.repeat(seconds % 4);
            console.log(`Loading audio${points}`);
          }, 1000);
        }
      }
    
      render() {
        return (
          
    ); } } ReactDOM.render(, document.getElementById("root"));
    sssccc
    sssccc
    
    

    reply
    0
  • Cancelreply