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:
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