Reputation: 83
I think this is a rather simple question, but I am trying to self-learn React.js and am a bit confused about how audio loops. I understand looping when rendering and returning plain html audio tags, but I am not sure how to do it without. So far I have learned how to toggle play and pause buttons thanks to another StackOverflow question I found, but am not sure how to make the audio loop as well. I would like to keep the current code if possible (I tried to use the audio tags mentioned above instead when rendering, but it was hard to re-incorporate the image toggling again) and just learn how to incorporate looping into it. Any help or resources would be much appreciated! Below is the code I have reduced it to so far:
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>
);
}
}
Upvotes: 6
Views: 10303
Reputation:
you can just set loop = true
togglePlay() {
this.setState({
play: !this.state.play
});
this.state.play ? this.audio.play() : this.audio.pause();
this.audio.loop = true;
}
Upvotes: 7