CORS错误播放来自另一个网站的mp3。

huangapple go评论53阅读模式
英文:

CORS error playing mp3 from another website

问题

我有一个问题,我的React应用程序无法播放来自另一个源的音频,出现CORS错误。
示例:https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3

奇怪的是,当我访问https://www.w3schools.com/tags/tag_audio.asp,输入上面的URL并点击播放时,它可以正常工作。

在我的本地React应用程序中,我得到了一个302状态和一个随后的重定向。音频标签包含crossOrigin="anonymous"以及src元素中的URL。

在W3Schools上,它以某种方式进行重定向,我只从重定向的URL得到状态206。

如何重现:

  1. 克隆https://github.com/SamTV12345/PodFetch.git
  2. 按照“构建”部分的README说明进行操作
  3. git checkout origin/develop
  4. 添加任何具有超过5集的播客。
  5. 单击CloudIcon
英文:

I have the problem that my React application does not play audio from another source with a CORS error.
Sample: https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3

Weirdly enough when I go to https://www.w3schools.com/tags/tag_audio.asp, enter the url from above and click play it works.

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

On W3Schools it does somehow the redirect and I only get a status 206 from the redirected url.

How to reproduce:

  1. git clone https://github.com/SamTV12345/PodFetch.git
  2. Follow the README description in the Building section
  3. git checkout origin/develop
  4. Add any podcast with more than 5 episodes.
  5. Click on the CloudIcon

答案1

得分: 1

你需要通过new Audio(url)导入mp3 URL,而不是使用XMLHttpRequest以避免CORS问题。例如:

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 (
      <div>
        <button
          id="audioBtn"
          onClick={this.togglePlay} onCanPlay={this.detectPlay}> {this.state.play ? "暂停" : "播放"}
        </button>
      </div>
    );
  }
}

ReactDOM.render(<PlaySound />, document.getElementById("root"));

CORS问题的示例使用Ajax:

let audio = document.querySelector('#myAudio');

function playAudio() {
  audio.play();
}

function pauseAudio() {
  audio.pause();
}

$.ajax({
  url: 'https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3',
  success: (res) => {
    audio.srcObject = URL.createObjectURL(res);
  },
  error: (err) => {
    console.error('CORS错误。请查看浏览器控制台以获取详细信息。');
  }
});
英文:

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

<!-- begin snippet: js hide: false console: true babel: true -->

<!-- language: lang-js -->

class PlaySound extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      play: false
    };

    this.url = &quot;https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3&quot;;
    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(()=&gt;{
        console.clear();
        let seconds = new Date().getSeconds();
        let points = &#39;.&#39;.repeat(seconds % 4);
        console.log(`Loading audio${points}`);
      }, 1000);
    }
  }

  render() {
    return (
      &lt;div&gt;
        &lt;button
          id=&quot;audioBtn&quot;
          onClick={this.togglePlay} onCanPlay={this.detectPlay}&gt; {this.state.play ? &quot;Pause&quot; : &quot;Play&quot;}
          
        &lt;/button&gt;
      &lt;/div&gt;
    );
  }
}

ReactDOM.render(&lt;PlaySound /&gt;, document.getElementById(&quot;root&quot;));

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt;

&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;

<!-- end snippet -->


Example occurrence of CORS with using Ajax:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let audio = document.querySelector(&#39;#myAudio&#39;);

function playAudio() { 
  audio.play(); 
} 

function pauseAudio() { 
  audio.pause(); 
} 

$.ajax({
  url: &#39;https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3&#39;,
  success: (res) =&gt; {
    audio.srcObject = URL.createObjectURL(res);
  },
  error: (err) =&gt; {
    console.error(&#39;CORS Error. See browser console for detail.&#39;);
  }
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;

&lt;audio id=&quot;myAudio&quot;&gt;&lt;/audio&gt;

&lt;button onclick=&quot;playAudio()&quot; type=&quot;button&quot;&gt;Play Audio&lt;/button&gt;
&lt;button onclick=&quot;pauseAudio()&quot; type=&quot;button&quot;&gt;Pause Audio&lt;/button&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月17日 01:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定