gpt4 book ai didi

reactjs - 使用 React.js 循环音频列表

转载 作者:行者123 更新时间:2023-12-03 00:25:54 24 4
gpt4 key购买 nike

我正在尝试自学 React.js,但我对音频列表的循环方式有点困惑。

我尝试构建一个可以播放声音的应用程序,但我遇到了无法循环播放音频列表的问题。目前,应用程序随机获取声音列表中的一个元素并播放,我仍然希望应用程序继续随机播放列表中的声音,直到我单击停止按钮。但目前,它只能重复一次,我不明白为什么。我做了谷歌搜索,但我找不到任何解决方案。
有人可以帮我吗?

这是我的尝试:

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"));

最佳答案

好像你在重置 this.audio在 updateAudio 方法中。我认为你应该绑定(bind)你的 'ended'再次事件监听器。

检查下面的代码

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()
}

关于reactjs - 使用 React.js 循环音频列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59497815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com