我认为这是一个非常简单的问题,但是我试图自学React.js,并且对音频的循环方式有些困惑。我理解呈现和返回纯HTML音频标签时的循环,但是我不确定如果没有该怎么做。到目前为止,由于我发现了另一个StackOverflow问题,我已经学会了如何切换播放和暂停按钮,但是还不确定如何使音频循环。我想尽可能保留当前代码(渲染时尝试使用上面提到的音频标签,但是很难再次合并图像以进行切换),只是学习如何将循环合并到其中。任何帮助或资源将不胜感激!下面是到目前为止我将其简化的代码:
export class PlaySound extends Component {
constructor(props) {
super(props);
this.state = {
play: true
};
this.url = "https://actions.google.com/sounds/v1/water/waves_crashing_on_rock_beach.ogg";
this.audio = new Audio(this.url);
this.togglePlay = this.togglePlay.bind(this);
}
togglePlay() {
this.setState({
play: !this.state.play
});
this.state.play ? this.audio.play() : this.audio.pause();
}
render() {
return (
<div>
<button
id="audioBtn"
onClick={this.togglePlay}> {this.state.play ? <PlayArrow /> : <Pause />}
</button>
</div>
);
}
}
答案 0 :(得分:2)
您可以在ended
对象中添加Audio
侦听器,在其中将时间设置回0
,然后重新开始播放。
class PlaySound extends Component {
constructor(props) {
super(props);
this.state = {
play: true
};
this.url = "https://actions.google.com/sounds/v1/water/waves_crashing_on_rock_beach.ogg";
this.audio = new Audio(this.url);
this.audio.addEventListener('ended', function () {
this.currentTime = 0;
this.play();
}, false);
this.togglePlay = this.togglePlay.bind(this);
}
// ...
}
class PlaySound extends React.Component {
constructor(props) {
super(props);
this.state = {
play: false
};
this.url = "https://actions.google.com/sounds/v1/water/air_woosh_underwater.ogg";
this.audio = new Audio(this.url);
this.audio.addEventListener('ended', function () {
this.currentTime = 0;
this.play();
}, false);
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()
}
}
render() {
return (
<div>
<button
id="audioBtn"
onClick={this.togglePlay}> {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>
答案 1 :(得分:1)
您可以只设置loop = true
togglePlay() {
this.setState({
play: !this.state.play
});
this.state.play ? this.audio.play() : this.audio.pause();
this.audio.loop = true;
}