我遇到的问题是,我的 React 应用程序无法播放来自其他来源的音频,并出现 CORS 错误。 示例:https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3
奇怪的是,当我访问 https://www.w3schools.com/tags/tag_audio.asp 时,输入上面的网址并单击播放即可。
在我的本地 React 应用程序上,我随后获得 302 状态和重定向。音频标记包含 crossOrigin="anonymous" 和 src 元素中的 url。
在 W3Schools 上,它会以某种方式进行重定向,我只从重定向的 URL 中获得状态 206。
如何重现:
P粉8019040892024-04-01 19:41:22
您需要通过 new Audio(url)
而不是 XMLHttpRequest
导入 mp3 URL,以避免 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 (); } } ReactDOM.render(, document.getElementById("root"));
sssccc sssccc