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:
You need to import the mp3 URL through 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 (
<div>
<button
id="audioBtn"
onClick={this.togglePlay} onCanPlay={this.detectPlay}> {this.state.play ? "Pause" : "Play"}
</button>
</div>
);
}
}
ReactDOM.render(<PlaySound />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Example occurrence of CORS with using 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 Error. See browser console for detail.');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="myAudio"></audio>
<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>