gpt4 book ai didi

reactjs - 使用 React.js 循环音频

转载 作者:行者123 更新时间:2023-12-02 22:13:34 25 4
gpt4 key购买 nike

我认为这是一个相当简单的问题,但我正在尝试自学 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>
);
}
}

最佳答案

您可以将 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>

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

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