如何通过 React / Redux 进行简单的 AJAX 调用来播放音频?
How can I do a simple AJAX call to play audio via React / Redux?
我正在尝试自动播放一些音频,但在 iOS 上,它不会自动播放。但是,如果我将它包装在 AJAX 调用中,它就会触发。所以这就是我所拥有的:
// run on page load
var audio = document.getElementById('audio');
jQuery.ajax({
url: 'ajax.js',
async: false,
success: function() {
audio.play(); // audio will play in iOS before 4.2.1
}
});
我该如何使用 React / Redux 进行设置?
这是一个非常简单的示例,它使用 fetch(大多数浏览器开箱即用都支持)和 blob
对象 URL。您当然也可以使用 jQuery 的 ajax
.
它与您的代码非常相似,但在 componentDidMount
方法中。 audio
元素通过 React's refs
.
引用
class Player extends React.Component {
componentDidMount() {
fetch(this.props.src)
.then(res => res.blob())
.then(blob => {
const { audio } = this.refs;
audio.src = URL.createObjectURL(blob);
audio.play();
});
}
render() {
return <audio ref="audio" controls></audio>;
}
}
ReactDOM.render(
<Player src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" />,
document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
❗️
此外,通常不建议在 React 中使用 refs
,但由于我们需要访问音频播放器的实际 DOM 节点,因此这是一个必要的邪恶。
我正在尝试自动播放一些音频,但在 iOS 上,它不会自动播放。但是,如果我将它包装在 AJAX 调用中,它就会触发。所以这就是我所拥有的:
// run on page load
var audio = document.getElementById('audio');
jQuery.ajax({
url: 'ajax.js',
async: false,
success: function() {
audio.play(); // audio will play in iOS before 4.2.1
}
});
我该如何使用 React / Redux 进行设置?
这是一个非常简单的示例,它使用 fetch(大多数浏览器开箱即用都支持)和 blob
对象 URL。您当然也可以使用 jQuery 的 ajax
.
它与您的代码非常相似,但在 componentDidMount
方法中。 audio
元素通过 React's refs
.
class Player extends React.Component {
componentDidMount() {
fetch(this.props.src)
.then(res => res.blob())
.then(blob => {
const { audio } = this.refs;
audio.src = URL.createObjectURL(blob);
audio.play();
});
}
render() {
return <audio ref="audio" controls></audio>;
}
}
ReactDOM.render(
<Player src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" />,
document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
此外,通常不建议在 React 中使用 refs
,但由于我们需要访问音频播放器的实际 DOM 节点,因此这是一个必要的邪恶。