我遇到的問題是,我的 React 應(yīng)用程序無法播放來自其他來源的音頻,并出現(xiàn) CORS 錯誤。 示例:https://audio.podigee-cdn.net/1041740-m-0fcf92e897e7cd93200a43cf103a75fb.mp3
奇怪的是,當(dāng)我訪問 https://www.w3schools.com/tags/tag_audio.asp 時,輸入上面的網(wǎng)址并單擊播放即可。
在我的本地 React 應(yīng)用程序上,我隨后獲得 302 狀態(tài)和重定向。音頻標(biāo)記包含 crossOrigin="anonymous" 和 src 元素中的 url。
在 W3Schools 上,它會以某種方式進行重定向,我只從重定向的 URL 中獲得狀態(tài) 206。
如何重現(xiàn):
您需要通過 new Audio(url)
而不是 XMLHttpRequest
導(dǎo)入 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