我正在尝试自学React.js,我对音频列表的循环方式有些困惑。
我试图构建一个可以播放声音的应用程序,但是我遇到了无法循环播放音频列表的问题。当前,该应用程序会随机从声音列表中获取一个元素并播放,我仍然希望该应用程序继续随机播放列表中的声音,直到单击“停止”按钮为止。但是目前,它只能重复一次,我不明白为什么。我进行了Google搜索,但找不到任何解决方案。 有人可以帮我吗?
这是我的尝试:
class PlaySound extends React.Component {
constructor(props) {
super(props);
this.state = {
play: false
};
// first link: 1s , second link: 7s
this.urls = ["https://actions.google.com/sounds/v1/water/air_woosh_underwater.ogg", "https://actions.google.com/sounds/v1/water/drinking_from_water_fountain.ogg"];
this.audio = new Audio(this.urls[0]);
this.audio.addEventListener('ended', this.updateAudio.bind(this), false);
this.togglePlay = this.togglePlay.bind(this);
}
updateAudio() {
const random = Math.floor(Math.random() * this.urls.length) + 0;
console.log(random)
this.audio = new Audio(this.urls[random]);
this.audio.play()
}
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"));
答案 0 :(得分:1)
似乎您在updateAudio方法中重置this.audio
。我认为您应该再次绑定'ended'
eventListener。
检查以下代码
updateAudio() {
const random = Math.floor(Math.random() * this.urls.length) + 0;
console.log(random)
// added below line.
this.audio = new Audio(this.urls[random]);
this.audio.addEventListener('ended', this.updateAudio.bind(this), false);
this.audio.play()
}